Minimal ListView Binding

May 9, 2012 at 7:51 am | Posted in HTML/JavaScript, Metro, Visual Studio 2011, Windows 8 | Leave a comment

Sometimes it is hard to see the forest for all of the trees. In learning the HTML5/JavaScript platform, I’ve relied on the plumbing of the Blank Application template in Visual Studio without understanding all of the functions. I recently responded to a forum query with an example of binding and updating a ListView with a super simple JavaScript that did not use the template.

This code has a ListView and a Button. The ListView is initialized from an array using a Binding.List. The bindings are declared in the markup. The Button click event triggers the addition of a new item to the list.

<body>
    <div id="myTemplate" data-win-control="WinJS.Binding.Template">
        <div data-win-bind="innerText: id"></div>
    </div>
    <button id="add">Add</button>
    <div id="myListView" data-win-control="WinJS.UI.ListView" data-win-options="{itemDataSource: Dataex.itemList.dataSource, itemTemplate:select('#myTemplate')}">
    </div>
</body>
(function () {
    "use strict";

    var dataArray = [{ id: "one" }, { id: "two" }]
    var dataList = new WinJS.Binding.List(dataArray);

    var p ={itemList: dataList};
    WinJS.Namespace.define("Dataex", p);

    function addItem() {
        dataList.push({ id: "three" });
    }

    WinJS.Utilities.ready(function () {
        document.getElementById("add").addEventListener("click", addItem, false);
        WinJS.UI.processAll();
    });

})();
Advertisements

Leave a Comment »

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.
Entries and comments feeds.

%d bloggers like this: