Saturday, 6 October 2012

Binding JSON data to a web page using Knockout JS

Knockout JS provides a nice way to bind data on HTML pages using JavaScript. It also helps in keeping the JavaScript code clean and separated. If you are not familiar with this library, check out the official site of Knockout JS.

In real time applications, there can be a number of scenarios in which data is obtained from a service using AJAX and the data obtained has to be displayed or updated on the page. Knockout’s observables cannot be applied directly on JSON data. The data needs some tweaks before applying it on the page.

For example, let’s assume the following JSON object is returned from the service:
var person = {
    "id": 10,
    "name": "Ravi",
    "designation": "Software Engineer"
};

To bind this data on the page using Knockout JS, a ViewModel object has to be defined with the properties that have to be made observable. Following is the ViewModel for the person class shown above:
var personVM = function () {
    var self = this;
    self.id = ko.observable();
    self.name = ko.observable();
    self.designation = ko.observable();
}

Data in the JSON object has to be mapped into a ViewModel object. The ViewModel object can be used to bind data on the page.
$(function () {
    var personVMObject = new personVM();
    personVMObject.id(person.id)
                  .name(person.name)
                  .designation(person.designation);
    ko.applyBindings(personVMObject);
});

The sample code is available on JSFiddle.

No comments:

Post a Comment