AI solution for JavaScript Coding Question on BFE.dev
154. Two-way binding
Here is a possible solution:
function model(state, element) {
// set initial value
element.value = state.value;
// listen to changes in input and update state
element.addEventListener('input', () => {
state.value = element.value;
});
// listen to changes in state and update input
Object.defineProperty(state, 'value', {
get() {
return this._value;
},
set(newValue) {
this._value = newValue;
element.value = newValue;
element.dispatchEvent(new Event('input'));
}
});
}
The model
function takes two arguments: state
, which is an object containing the initial value (in this case, { value: 'BFE' }
), and element
, which is the HTMLInputElement to bind.
The first thing the function does is set the initial value of the input by setting element.value
to state.value
.
Then, the function adds an event listener to the input that listens for changes (using the 'input'
event) and updates the state by setting state.value
to element.value
.
Finally, the function defines a getter and setter for state.value
using Object.defineProperty
. The getter simply returns this._value
, which is the internal value that will be used to store the state. The setter updates this internal value, updates the input's value to the new value, and dispatches an 'input'
event to trigger the event listener we added earlier.
With this two-way binding set up, changes to the input will update the state, and changes to the state will update the input.