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.

    <div id="myTemplate" data-win-control="WinJS.Binding.Template">
        <div data-win-bind="innerText: id"></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')}">
(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);


Simple data binding example

April 30, 2012 at 10:06 am | Posted in HTML/JavaScript, Metro, Windows 8 | Leave a comment

{Code updated to reflect changes in Release Preview.}

I was trying add a simple piece of markup that had text elements bound to an object, but just could not get it to work the way I wanted, i.e. declare a binding source in the markup. By looking at the samples, I could use WinJS.BindingAll(element, object), but for some reason failed with data-win-bindsource in the markup. Finally, I did a Google search on “data-win-bindsource” and ran across a post in November 2011 that was exactly what I was trying to do. It turns out that the answer provider was me!

So for the sake of others who are trying to do the same thing and for pounding this nugget into my own brain, here is the example:

    <div class="fixed-layout">
        <div data-win-bindsource="">
            <div data-win-bind="innerText: x"></div>
        <button id="myButton">

(function () {
    "use strict";
    var person = {
        name: "Tom",
        city: "Boston"

    var labelSource =;

        WinJS.UI.processAll().then(function () {
            var elem = document.querySelector("#complexLabel");
            WinJS.Binding.processAll(elem, labelSource);

        var lab = document.getElementById("complexLabel");
        document.getElementById("action").addEventListener("click", changeLabel, false);

    function changeLabel() { = "John"; = "New York";

    //Make names public with namespace so that HTML file can see them
    WinJS.Namespace.define('test', {
        labelSource: labelSource

Reading a text file from the app package

April 23, 2012 at 5:37 pm | Posted in HTML/JavaScript, Metro, Windows 8 | Leave a comment

This is an example of how to read a text file that is embedded in the app package.

 //Read a text file in the 'data' folder in the app package.
    //Outputs the contents to the console
    function getDataFromPackage(fileName) {
        var myPackage = Windows.ApplicationModel.Package.current;
        var instLocation = myPackage.installedLocation;
        var path = "data\\" + fileName;
        .then(function (file) {
            return Windows.Storage.FileIO.readTextAsync(file);
        }).done(function (myText) {

Background task pollution

April 22, 2012 at 1:21 pm | Posted in HTML/JavaScript, Metro, Windows 8 | Leave a comment

I am developing a Metro HTML/JavaScript application which uses a background task to notify the user of updates to some data that is collected periodically. Initally, the background task simply read the data, did some filtering and sent a tile notification. This all seemed to be working well. When I added a toast notification; however, I began to see some strange behavior.

First, I noticed that when the background task fired based on a timer, that dozens of processes seemed to appear in the Visual Studio debugger. Second, I found that the toast was triggered multiple times for each interval. Of course, this continued even if the program was no longer running. It occurred after a reboot also.

My suspicion was that the background task was registered multiple times. My program was configured to register the background task every time it was launched. I assumed that the system would just overwrite the previous registration with the new one. It appears, though that each registration is added to a list of registrations even if they are identical. After numerous debug sessions, these registrations were adding up. I was polluting the background task manager.

The programmatic solution to this problem is to unregister all of the tasks associated with the program using the following routine:

function unregisterBackgroundTasks(taskName) {
        // Loop through all background tasks and unregister any with the taskName
        var iter = Windows.ApplicationModel.Background.BackgroundTaskRegistration.allTasks.first();
        var hascur = iter.hasCurrent;
        while (hascur) {
            var cur = iter.current.value;
            if ( === taskName) {
            hascur = iter.moveNext();

This seems to work well but I do not know if there is a way to clear this “pollution” of the background task manager outside of the program except that background tasks are unregistered when a program is uninstalled.

Updating Metro tiles in the background periodically

April 20, 2012 at 9:00 am | Posted in HTML/JavaScript, Metro, Windows 8 | 3 Comments

This is an example of how to use a background task to update an app’s tiles.

First, here is a default html file with a button and status line.

<!DOCTYPE html>
    <meta charset="utf-8">

    <!-- WinJS references -->
    <link href="//Microsoft.WinJS.0.6/css/ui-dark.css" rel="stylesheet">
    <script src="//Microsoft.WinJS.0.6/js/base.js"></script>
    <script src="//Microsoft.WinJS.0.6/js/ui.js"></script>

    <!-- HelpTileUpdate references -->
    <link href="/css/default.css" rel="stylesheet">
    <script src="/js/default.js"></script>
    <button id="startService">Start Background</button>
    <div id="status">Status of service</div>

Next, the default.js which handles the button click event.   This handler requests to use the lock screen (required for timer background tasks) and then registers the task with a timeTrigger set for 15 minutes (the minimum allowed interval).

// For an introduction to the Blank template, see the following documentation:
(function () {
    "use strict";

    var app = WinJS.Application;

    app.onactivated = function (eventObject) {
        if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
            if (eventObject.detail.previousExecutionState !== Windows.ApplicationModel.Activation.ApplicationExecutionState.terminated) {
                // TODO: This application has been newly launched. Initialize
                // your application here.
            } else {
                // TODO: This application has been reactivated from suspension.
                // Restore application state here.
            WinJS.UI.processAll().then(function onComplete(processedElements) {
                document.getElementById("startService").addEventListener("click", beginBackgroundService, false);

    app.oncheckpoint = function (eventObject) {
        // TODO: This application is about to be suspended. Save any state
        // that needs to persist across suspensions here. You might use the
        // WinJS.Application.sessionState object, which is automatically
        // saved and restored across suspension. If you need to complete an
        // asynchronous operation before your application is suspended, call
        // eventObject.setPromise().


    function beginBackgroundService() {


    function displayStatus(msg) {
        document.getElementById("status").innerText = msg;

    function registerBackgroundTask() {
        var builder = new Windows.ApplicationModel.Background.BackgroundTaskBuilder(); = "myTask";
        builder.taskEntryPoint = "backgroundtask.js";
        var timeTrigger = new Windows.ApplicationModel.Background.TimeTrigger(15, false);
        //var timeTrigger = new Windows.ApplicationModel.Background.SystemTrigger(Windows.ApplicationModel.Background.SystemTriggerType.timeZoneChange, false);
        var conditionType = Windows.ApplicationModel.Background.SystemConditionType.internetAvailable;
        var taskCondition = new Windows.ApplicationModel.Background.SystemCondition(conditionType);
        var backgroundTaskRegistration = builder.register();


    // This is a helper function to add your app to the lock screen.
    // Time events require the app to be on the lock screen to fire
    function requestLockScreenAccess() {
        var Background = Windows.ApplicationModel.Background;

        // An app can call the add or query API as many times as it wants; however, it will only present the dialog box to the user one time.
        Background.BackgroundExecutionManager.requestAccessAsync().then(function (result) {
            switch (result) {
                case Background.BackgroundAccessStatus.denied:
                    displayStatus("This app is not on the lock screen.");

                case Background.BackgroundAccessStatus.allowedWithRealTimeConnectivity:
                    displayStatus("This app is on the lock screen and has access to Real Time Connectivity.");

                case Background.BackgroundAccessStatus.allowedWithoutRealTimeConnectivity:
                    displayStatus("This app is on the lock screen, but does not have access to Real Time Connectivity.");

                case Background.BackgroundAccessStatus.unspecified:
                    displayStatus("The user has not yet taken any action. This is the default setting and the app is not on the lock screen.");
        }, function (e) {

Next, you will need to add a backgroundtask.js file to your project. This code simply checks the date and writes it to a wide tile.

//Background task
//Checks for new events and notifies user.
//Updates tiles

(function () {
    "use strict";


    //Begin task
    var backgroundTaskInstance = Windows.UI.WebUI.WebUIBackgroundTaskInstance.current;

    var notifications = Windows.UI.Notifications;

    var date = new Date();

    backgroundTaskInstance.succeeded = true;

    function displayTileNotification(content) {
        // get a filled in version of the template by using getTemplateContent
        var tileXml = notifications.TileUpdateManager.getTemplateContent(notifications.TileTemplateType.tileWideText01);

        // get the text attributes for this template and fill them in
        var tileAttributes = tileXml.getElementsByTagName("text");

        var title = "Tile Updated At";

        // create the notification from the XML
        var tileNotification = new notifications.TileNotification(tileXml);

        // send the notification to the app's default tile


Finally, you need to configure the manifest. Double-click package.manifest to bring up the wizard.

  1. In the Application UI tab, change Lock screen notifications to Badge and Tile Text
  2. Supply pointers to a wide tile image and badge image of the required sizes.
  3. In the Declarations tab, add a Background Task
  4. Select Timer
  5. Add backgroundtask.js in the field for Start Page

Run the program.  Click the button and the first time, you will be prompted to enable lock screen access.  Allow it.

Watch the Start Screen.  Find your tile and change it to wide format.  Wait.  The tile should update in 15-30 minutes then every 15 minutes thereafter even if the program is terminated.



Tip for debugging JavaScript metro apps

April 5, 2012 at 7:52 am | Posted in HTML/JavaScript, Metro, Visual Studio, Windows 8 | Leave a comment

With the release of the Windows 8 beta, I’ve been playing around again with metro apps made with HTML/JavaScript.  I was frustrated with debugging situations in which portions of code just didn’t seem to execute while displaying no error messages.  Then yesterday, I discovered this.  It explains that code with Promises deals with runtime errors in a special way and expects error handling routines to react to appropriately.

It is helpful to make sure that the Visual Studio menu item Debug > Exceptions > JavaScript Runtime > Thrown is selected.  This should expose errors that the runtime has detected but is ‘holding’ for some handling routine that is often not yet implemented.

Next Page »

Blog at
Entries and comments feeds.