What do current frameworks emphasize on one-way binding and what are two-way binding?
- One-way data binding: It means that we write the template first, then integrate the template and data (the data may come from the background) to form HTML code, and then insert this HTML code into the document flow.
- Two-way data binding: Two-way binding between data model (Module) and view (View). That is, no matter whether I modify the relevant data of the data model or the data on the view, the corresponding data will be updated accordingly.
The main thing is the binding of events.
- On the view layer (View), you can bind the keyup event to update the data model
- Use the Object.defineProperty() method on the data model to define the set method of the object. When the object property setting is triggered, Also modify the data in the view layer.
Title
First, we first use the Object.defineProperty() method to set the set method of obj, as long as we modify the input of obj Attribute, this set method will be triggered, and then the callback will be triggered, which realizes the data binding of the module layer.
Then, bind the keyup event on the input to realize the binding of the view layer.
As long as there is a modification between the two, regardless of the value of input or the input attribute of obj, the latest modified value will be obtained.
This should be the simplest idea.
The above is the detailed content of How to implement two-way data binding in js. For more information, please follow other related articles on the PHP Chinese website!