WinRT JavaScript - Templates & Data Binding
Written by Ian Elliot   
Article Index
WinRT JavaScript - Templates & Data Binding
Templates and data
Data binding
The databound table

The databound table

 

 

 

As a slightly more complex example let's go back to the table but this time add the data using data binding. First we need to revise the HTML to include data-win-bind attributes:

<div id="Mytemplate" data-win-control=
"WinJS.Binding.Template">
<table>
<tr>
<td data-win-bind="innerText:cell1">
</td>
<td data-win-bind="innerText:cell2">
</td>
<td data-win-bind="innerText:cell3">
</td>
</tr>
</table>
</div>

<table id="Display" border="1">
</table>

You can see that each of the <td> tags innerText property is bound to the cell1, cell2 and cell3 properties of the data source and the table row initially has no data.

The JavaScript is simple too:

var template = Mytemplate.winControl;
template.render(
{ cell1: "This is cell 1",
cell2: "This is cell 2",
cell3: "This is cell 3"
}).then(
function (element) {
var tr = element.firstElementChild.
firstElementChild.firstElementChild;
Display.appendChild(tr);
});       

When you run this the table appears  with a single row and the contents as specified by the data source object.

 

table2

 

Of course you could have created the data source object else where in the program. The complete code using a separate variable to hold the data source object is:

WinJS.UI.processAll();

var template = Mytemplate.winControl;
var data = {
cell1: "This is cell 1",
cell2: "This is cell 2",
cell3: "This is cell 3"
};
template.render(data).then(
function (element) {
var tr = element.firstElementChild.
firstElementChild.firstElementChild;
Display.appendChild(tr);
});

Where next

It has to be admitted that templates and data binding are of most use when use a ListView or other more complicated WinJS control. The idea behind using a table and other HTML elements with the Template and data binding was to try and illustrate that there is nothing really out of the ordinary going on. The Template object simply renders the elements within the template and sets the specified properties to the values specified in the data source.

You should be able to see how you would implement this mechanism from scratch for yourself using nothing but standard HTML and JavaScript.

To see how useful all of this is, we have to take a look at the ListView and related controls and delve more deeply into data binding.

 

 

To read more of this book click its cover image:

cover

 

 

espbook

 

Comments




or email your comment to: comments@i-programmer.info

 

+        className    "win-template"    String
+        className    "win-template"    String