One Way Data Binding In WinJS

Introduction
Data binding is one of the key feature in the application development. One way data binding is the way to reflect the data in the control from a model. Any up-gradation made to the data in the model it will reflect in the control to which it is bound.

One way data binding
Below is a one way binding application example to see how it is really working. Let’s add a page item to the project. This will add 3 files in general. One JS file, Html file and a CSS file with the same name specified for the page item.

HTML File Content

<div id="dataDiv">
<input type="text" id="txtName" data-win-bind="value:name" />
<input type="button" id="btnChangeName" value="Change Name"/>
</div>

JS file contents

var myDataModel = { id: 10, name: "Nirmal" };

app.onready = function (args) {

var dDiv = document.getElementById("dataDiv");

WinJS.Binding.processAll(dDiv, myDataModel);

var objCol = WinJS.Binding.as(myDataModel);

var NameChangeButton = document.getElementById("btnChangeName");

NameChangeButton.addEventListener("click", function () {

if (objCol.name == "Mindfire") {

objCol.name = "Nirmal";

}
else {
objCol.name = "Mindfire";
}
});
}

 Expansion

In the above JS file we have created a model with 2 fields such as Name and ID.

WinJS.Binding.processAll(dDiv, myDataModel);

In the above line of code, we have bind the model to the parent div and the controls are bound to individual properties. Now the next step is to create an observable collection, where any change to the model data gets reflected in the control.

var objCol = WinJS.Binding.as(myDataModel);

Here objCol is the obervable collection we have made out of the original data model we have. To test the same we have bind the button with a click event. In the click event the button tries to change the name and it is getting reflected in the text box control.

Written By: Nirmal Hota, X-platform Mobile Lead, Mindfire Solutions

Advertisements

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