I play with Microsoft's suggestion for jQuery Templates and Data Binding, and so far this is awesome.
TL; DR, check out this demo .
Itβs very easy to link a piece of HTML to a JavaScript object and from there update only the JavaScript object and HTML updates.
Here is a simple example. Create the HTML that will represent your widget.
<div class="book"> <img width="100" height="100" src="" /> <div class="title"></div> <div class="price"></div> </div>
Then create a JavaScript object and dynamically link it to the HTML above. Here is an example object:
var book = { title: "Alice in Wonderland", price: 24.99, onSale: true, image: "http://bit.ly/cavCXS" };
Now to the actual link. Elements we are going to relate:
- And the
data-onsale attribute in the outer div, which will be either "true" or "false" - Image
src attribute for the image property of our book - title div for title property
- price div for the price.
Listed below are links. Please note that we only do one method related here, but you can also configure two-way communication using the linkBoth function.
$(book) .linkTo('title', '.title', 'html') .linkTo('price', '.price', 'html') .linkTo('image', '.book img', 'src') .linkTo('onSale', '.book', 'data-onsale')
What is it. From now on, just update the book object and the HTML will automatically update. Update the book properties as if you had updated the html attributes with the attr function.
$(book).attr({ price: 14.75 });
or
$(book).attr('price', 14.75);
The code above uses only data binding, but the proposal also mentions combining data with templates, which would make it even easier. From what I believe you could do this and get the above functionality:
<script id="bookTemplate" type="text/html"> <div class="book" data-onsale="{{link onSale }}"> <img width="100" height="100" src="{{link image }}" /> <div class="title">{{link title }}</div> <div class="price">{{link price }}</div> </div> </script>
Link the above template to the book object in one step and add it to the page:
$('#bookTemplate').render(book).appendTo('body')
Update the properties of the book object and the changes will be reflected.