jQuery模板技术和数据绑定实现代码

2020-05-22 17:03:51易采站长站整理


The following JavaScript code links the two INPUT elements above to the properties of a JavaScript “contact” object that has a “name” and “phone” property:


image


When you execute this code, the value of the first INPUT element (#name) is set to the value of the contact name property, and the value of the second INPUT element (#phone) is set to the value of the contact phone property. The properties of the contact object and the properties of the INPUT elements are also linked – so that changes to one are also reflected in the other.


Because the contact object is linked to the INPUT element, when you request the page, the values of the contact properties are displayed:


image


More interesting, the values of the linked INPUT elements will change automatically whenever you update the properties of the contact object they are linked to.


For example, we could programmatically modify the properties of the “contact” object using the jQuery attr() method like below:


image


Because our two INPUT elements are linked to the “contact” object, the INPUT element values will be updated automatically (without us having to write any code to modify the UI elements):


image


Note that we updated the contact object above using the jQuery attr() method. In order for data linking to work, you must use jQuery methods to modify the property values.


Two Way Linking


The linkBoth() method enables two-way data linking. The contact object and INPUT elements are linked in both directions. When you modify the value of the INPUT element, the contact object is also updated automatically.


For example, the following code adds a client-side JavaScript click handler to an HTML button element. When you click the button, the property values of the contact object are displayed using an alert() dialog:


image


The following demonstrates what happens when you change the value of the Name INPUT element and click the Save button. Notice that the name property of the “contact” object that the INPUT element was linked to was updated automatically:


image