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

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


image


When the page is loaded, the list of contacts is rendered by the template.  All of this template rendering is happening on the client-side within the browser:


image 


Templating Commands and Conditional Display Logic


The current templating proposal supports a small set of template commands – including if, else, and each statements. The number of template commands was deliberately kept small to encourage people to place more complicated logic outside of their templates.


Even this small set of template commands is very useful though. Imagine, for example, that each contact can have zero or more phone numbers. The contacts could be represented by the JavaScript array below:


image


The template below demonstrates how you can use the if and each template commands to conditionally display and loop the phone numbers for each contact:


image


If a contact has one or more phone numbers then each of the phone numbers is displayed by iterating through the phone numbers with the each template command:


image


The jQuery team designed the template commands so that they are extensible. If you have a need for a new template command then you can easily add new template commands to the default set of commands.


Support for Client Data-Linking

The ASP.NET team recently submitted another proposal and prototype to the jQuery forums (http://forum.jquery.com/topic/proposal-for-adding-data-linking-to-jquery). This proposal describes a new feature named data linking. Data Linking enables you to link a property of one object to a property of another object – so that when one property changes the other property changes.  Data linking enables you to easily keep your UI and data objects synchronized within a page.


If you are familiar with the concept of data-binding then you will be familiar with data linking (in the proposal, we call the feature data linking because jQuery already includes a bind() method that has nothing to do with data-binding).


Imagine, for example, that you have a page with the following HTML <input> elements:


image