There are few ways to perform data-binding with template in Windows8 metro app using HTML5/JS.
I will try to capture some of the data-binding options using template with WinJS.UI.ListView as an example control.
DataExample.itemList.dataSource is the object containing the list of names { name: "Hello" }.
I will try to capture some of the data-binding options using template with WinJS.UI.ListView as an example control.
DataExample.itemList.dataSource is the object containing the list of names { name: "Hello" }.
- Simple data binding: (Declarative)
< div id="mediumListIconTextTemplate"
data-win-control="WinJS.Binding.Template" >
<div >
<!-- Displays the "title" field. -->
<input type="text" data-win-bind="innerText: name"> /input>
</div>
</div>
<div id="myFriends"
data-win-control="WinJS.UI.ListView"
data-win-options="{
itemDataSource : DataExample.itemList.dataSource,
itemTemplate: mediumListIconTextTemplate
}">
</div>
This simple binding would work if there are no nested pages.
- Binding when there are navigation involved (Declarative)
If there are navigation pages involved then use Select('#<YourTemplateId>') . Rest of the code remains same as in Simple data binding.
- Template in Javascript (programmatically)
Another way to create a template is in the javascript. You can create template as a javascript object in your .js file.
var mediumListIconTextTemplate WinJS.Utilities.markSupportedForProcessing(function mediumListIconTextTemplate(itemPromise) {
return itemPromise.then(function (currentItem) {
var result = document.createElement("div");
// Display name
var displayName = document.createElement("input");
displayName.type = "text";
displayName.value = currentItem.data.name;
result.appendChild(displayName);
return result;
});
});
Make sure to use "currentItem.data" when accessing the properties. For every item in the collection, the function mediumListIconTextTemplate is called.
You can also add event handlers similar to any standard js code.
displayName.addEventListener("change", function (event) {
// Code to handle on change event here
});
Programmatically creating the template gives high flexibility and handling the elements at a very granular form. But it increases the number of lines of code.
If you want simple binding (readonly without events), I suggest to use simple binding. But if you want more control on your template, then programmatically creating a template would be an option.