WinJS Binding: Binding Initializers

Binding in WinJS is one-way binding. A bound object listens for changes to the source property and updates its contents. This binding is commonly used to make the UI responsive to underlying data changes in the source object. However, since the binding is one-way, changes to the UI are not reflected in the data object.

A binding relationship is established by using the custom attribute data-win-bind. Data-win-bind binds a source element, which is some data stored in a variable, to a target element, which can be a UI control, in the following fashion:

data-win-bind= “<targetProperty> : <sourceProperty> [<initializer>]”

The initializer argument is optional, defaulting to WinJS.Binding.defaultBind. Writing your own initializer function lets you manipulate the data beyond simply copying the source to the target.

Alterntively, you can use WinJS.Binding.setAttribute. This is similar to the defaultBind initializer except it injects the information into the target's setAttribute method. This is useful if the target does not have a property defined in JavaScript.

One-time Binding

In one-time binding, the value of the “source property” is transferred to the “target property” and they have no further relationship. One-time binding let us make assignments directly to element attributes even with declarative initialization.

To initialize the data-win-bind for one-time binding, we use WinJS.Binding.oneTime.

data-win-bind="innerText: name WinJS.Binding.oneTime"

Alternatively, like the setAttribute above, we can use WinJS.Binding.setAttributeOneTime which does exactly what it sounds like.