Click here to Skip to main content
Click here to Skip to main content
Technical Blog

Windows 8 App Development - JavaScript (Data)Binding

, 27 Aug 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
Windows 8 application development using the WinJS framework - DataBinding.

This is my fourth blog post related to Windows 8 Application Development with HTML5, CSS3 and JavaScript. You can find the previous ones on my blog's main page.

Last time I presented the HouseRental project, which is a very simple one, you can check the code on GitHub. In this project all data is simply written inside the default.html file, the only JS (JavaScript) code existed was generated by Visual Studio 2012 RC from the blank project template.

This time I will take a step further and improve the HouseRental application. I will do two things:

  1. Store the data in JavaScript objects.
  2. Use data-binding to display data from JavaScript objects to HTML elements.

You can take a look at the source code at GitHub. I've named the project HouseRental_Binding.

For web developers it is not clear what are you referring to when are talking about bindings. Most of them work a lot with jQuery and the first thing which comes in their minds is the bind() method from jQuery API and clearly we are not referring to that when talking about Windows 8 App Development. So we should be more precise, I will stick with data-binding expression from now-on. I mentioned jQuery, but I am pretty sure from those who are reading this post right now, have heard about knockout.js. I had the opportunity to use it in real projects. Having a more solid desktop application development background and some WPF knowledge I had no problem applying the MVVM pattern. Who has not heard about the MVVM design pattern, do not panic, if you heard and know about MVC you'll understand MVVM in a blink of an eye.
 
I'm writing about MVVM because the Windows 8 Application Development embraces this design pattern. If you are not familiar with it, in a short period of time you'll understand it's benefits.

The CSS story...

I have not made any change to the design of the application. The default.css file was not modified, it's exactly the same as it was in the HouseRental project.

The HTML5 story...

To apply the data-bindigs the default.html file has to be changed. I deleted the hard coded data, and added attributes to the HTML tags, here is an example:
<!-- HOUSE 1 -->
    <div id="topLeftContainer" class="gridLeft">
        <h2 data-win-bind="innerText: Data.city1"></h2>
        <div class="contentContainer">
            <img data-win-bind="src: Data.imageSource1"/>
            <div class="price">
                <data-win-bind="innerText: Data.price1"></h4>
            </div>
        </div>
    </div>

The data-win-bind attribute is set to a key : value pair. The key is a property of the HTML element, the value is a property from the data source of the container. In this case this will cause to bind the value from data source property Data.city1 / Data.imageSource1 / Data.price1 to the innerText / src / innerText property of the HTML tag. There is some additional information related to  data-win-bind on MSDN.

The JavaScript story...

Most of the changes occur in the JS code. A new JS file was added in the js folder of the application, data.js. The content can be seen below:
/// <reference path="//Microsoft.WinJS.0.6/js/base.js" /> 
/// <reference path="//Microsoft.WinJS.0.6/js/ui.js" /> 

 (function () {
    "use strict";

    WinJS.Namespace.define("ViewModel.Data", {
        price1: "",
        price2: "",
        price3: "",
        price4: "",

        imageSource1: "",
        imageSource2: "",
        imageSource3: "",
        imageSource4: "",

        city1: "",
        city2: "",
        city3: "",
        city4: ""
    });

    //init prices
    ViewModel.Data.price1 = "650.000 $";
    ViewModel.Data.price2 = "890.000 $";
    ViewModel.Data.price3 = "380.000 $";
    ViewModel.Data.price4 = "740.000 $";

    //init image sources
    ViewModel.Data.imageSource1 = "/images/house1.jpg";
    ViewModel.Data.imageSource2 = "/images/house2.jpg";
    ViewModel.Data.imageSource3 = "/images/house3.jpg";
    ViewModel.Data.imageSource4 = "/images/house4.jpg";

    //init the cities
    ViewModel.Data.city1 = "New York";
    ViewModel.Data.city2 = "Los Angeles";
    ViewModel.Data.city3 = "Boston";
    ViewModel.Data.city4 = "San Francisco";

 })();
The first two lines of  the file with the /// <reference ... />  cause the "import" of the two named files. These references are also used by the Visual Studio's IntelliSense. Who have ever worked with  the Cassette.Web project (it can be downloaded from NuGet package gallery) for those these kind of reference declarations are familiar (The idea behind the Cassette.Web project is, to include only the required .css and .js files into a webpage. It helps you build up assets and bundles which can be referenced afterwards from server side code in ASP.NET MVC projects.  This tool helps to create a cleaner and faster website).

After the references have been declared comes a self executing JavaScript function. I wrote about the "use strict" declaration in one of my previous blog post, so I will not detail this, you can read more about it on MSDN.

The line WinJS.Namespace.define("ViewModel.Data", { causes to define a new object (the second parameter of the define function) which will be assigned to the namespace written in the first parameter. In the current example this means, that after the:

WinJS.Namespace.define("ViewModel.Data", { ... }); 
line of code is executed a new object will be available which can be accessed through the ViewModel.Data property as it can be seen in the init prices, init image sources and init the cities code region.

To view from a higher level, all I did in this data.js file was, to declare in the ViewModel.Data namespace a new object with 12 public properties initialized with empty strings. After the declaration I assign new values to the public properties. 

So, the default.html file was changed to have bindings towards JavaScript objects, the JavaScript objects were created but these two have to be connected, otherwise it won't work. To connect the HTML bindings and the JS objects some changes has to be made in the default.js file.

The only thing changed is that a new function was added and this is invoked when the application is launched.

function init() {
        WinJS.Binding.processAll(document.body, ViewModel);
}
The init() function, invokes the processAll(...) method with two parameters, the first one refers to the HTML elements where the binding should occur, the second one is the object (dataContext) which stores the data.

The init() function is invoked in the handler of onactivated:

app.onactivated = function (args) {
    if (args.detail.kind === activation.ActivationKind.launch) {
        if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
            // TODO: This application has been newly launched. Initialize
            // your application here.

           init();

        } else {
            // TODO: This application has been reactivated from suspension.
            // Restore application state here.
        }
        args.setPromise(WinJS.UI.processAll());
    }
};
When the application is launched, the onactivated event occurs and the handler assigned to this event is invoked; the init() function is invoked also, this calls the processAll() method of Bindings namespace and this, together with the HTML attributes (data-win-bind) will resolve the binding between JS objects and HTML tags.

In the next posts I will present two way bindings, observable collections, and templates.  

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Gergo Bogdan
Software Developer
Hungary Hungary
I'm a software engineer who likes challenges, working in a team, I like learning new things and new technologies. I like to work with cutting edge technologies, I like to help out my collegues and team members. I have experience in building Desktop Applications based on .NET WPF and WinForms technologies. I used Silverlight for Web Application Development, but I'm also familiar with HTML5, CSS3, ASP.NET MVC, JavaScript and jQuery.
 
Recently, I work as a full time Java backend developer.
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
GeneralMy vote of 5 PinmemberChristian Amado27-Aug-12 10:17 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.141216.1 | Last Updated 27 Aug 2012
Article Copyright 2012 by Gergo Bogdan
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid