Tag Archives: binding

Creating a Bindable object in javascript for Windows store application

Published April 8, 2013 6:57 pm

When I was writing windows store application in c#, it provided

class BindableBase

I was looking for similar way to create bindable object in javascript using WinJS library. WinJS libray does have WinJS.Binding.as() method that can be used to make an object observable through a proxy. but I was looking for a way to make the object itself Observable.

var MyViewModel = WinJS.Class.define(
    function MyViewModel_ctor()
    {
        this._initObservable();
        this.bind('property1', this._onproperty1change.bind(this));
    },
    {
        _onproperty1change: function onproperty1change(newValue)
        {
            // can be used to update properties that are dependent on property1
            // property3 and property4 for example - can be updated here. UI will be 
            // notified if it is binding to these properties
        },
    });

    WinJS.Class.mix(MyViewModel,
        WinJS.Binding.mixin,
        WinJS.Binding.expandProperties({ property1: '', property2: ''}));

With little help from the quickstart and reading the WinJS base.js class helped arrive to this code and understand how it works.

var expandProperties = function (shape) {
    var props = {};
    function addToProps(k) {
        props[k] = {
            get: function () { return this.getProperty(k); },
            set: function (value) { this.setProperty(k, value); },
            enumerable: true,
            configurable: true // enables delete
        };
    }
    while (shape && shape !== Object.prototype) {
        Object.keys(shape).forEach(addToProps);
        shape = Object.getPrototypeOf(shape);
    }
    return props;
};
  1. WinJS.Binding.expandProperties documentation won’t help to understand what it brings. The snippet from the base.js above clarifies that it adds properties for each key specified in the parameter, and the value specified is not used for anything.
  2. WinJS.Binding.mixin object brings the getProperty/setProperty/bind/notify and bunch of other methods for the object
  3. _initObservable() need to be invoked from the constructor to initialize _backingData field. The _backingData object is used to store the property values.
  4. this.bind helps you get notified for a property change, and it can help in scenario like updating dependent properties.
  5. It saves writing boiler plate code for each property in the view model object

Did you need something like this? Have you solved in different way than this?