WinJS Binding: Binding Lists
Now that we've seen how WinJS binds information to attributes and elements, we'll look at how data can be more efficiently passed, through Binding Lists.
A Binding List is an observable array, which is just like a normal array except any addition, deletion or change to the array triggers an event that updates the Binding List. You can create a list by making an empty list and using push()
to populate the list. The more common way is to create a list based off of an array like:
var dataArray = [
{name: "Marley", species: "dog"},
{name: "Lola", species: "cat"},
{name: "Leo", species: "dog"},
{name: "Izzy", species: "cat"},
{name: "Ziggy", species: "cat"},
{name: "Ruby", species: "dog"},
];
var dataList = new WinJS.Binding.List(dataArray);
Here, the array of objects “dataArray” was turned into a WinJS.Binding.List
by using the constructor to make a new Binding List dataList
WinJS has a WinJS.Binding.List
object type, used to turn arrays into Binding Lists. This WinJS.Binding.List
object is the centerpiece of data-binding collections of information and can contain any type of value, including complex structures like objects and arrays. However, changes to an object array may not be observable.
Repeaters
A Repeater generates HTML from a set of data, which is represented through a Binding List, and repeats it until all of the data is displayed.
To load the data from the data-win-bind
, you can load them into their respective attributes. We have listed a few basic ones that we will use below:
Data-binding attributes
- textContent: Text content to be loaded in an element
- src: Specifies the URL destination of an element
- value: Specifies the value to be sent to a server
Now you can see these attributes being set below. Here is the HTML for the Repeater pulling from myList, an object hanging off the window object:
<select data-win-control:
WinJS.UI.Repeater" data-win-options="
{data:myList.items}>
<option data-win-bind="value:id; textContent: description">
</option>
</select>
Do note though that the Repeater control can only repeat a single HTML root element. However, you can create a div to wrap as many elements as you want to be repeated.
Try It Out
Check It Out
In the JS:
- Create a new Binding List from the trailArray variable in the data property of the myList object.
//create a binding list out of the trailArray we just created
var myList = window.myList = {
data: new WinJS.Binding.List(trailArray)
};
In the HTML:
- Add the Repeater constructor to the
data-win-control
and the object property holding your Binding List to thedata-win-options
.
<div data-win-control="WinJS.UI.Repeater" data-win-options="{data: myList.data}">
<div>
<h2 style="display: inline-block" data-win-bind="textContent: title"></h2>
<div class="win-small" data-win-control="WinJS.UI.Rating" data-win-bind="winControl.userRating: averageRating"></div>
</div>
</div>
Check the output, to see if the list of trails shows.
Are you sure you want to do this?