WinJS observables (Part III) - using WinJS.Binding.define

In my previous blog post I showed first possible solution to WinJS observables pitfalls. Let's see another.



Just repeat again what's our goal in BDD style:

AS a developer

I WANT to be able to define observable properties on the class as well as other class parts: get/set properties and methods and I don't want to pay any unnecessary performance penalties

SO THAT the observable object will be able to notify listeners that the property has changed



The previous solution has the problem that we had raise property change manually. In this blog post we try to use more WinJS.

In order to make the class observable we mix into class all required mixins (already done in previous post) but now, let's do it in the different way. Let's define a helper method:

 function observableClass(ctor, instanceMembers, staticMembers) {
    var baseClass = WinJS.Binding.define(instanceMembers);

    return WinJS.Class.derive(baseClass, function () {;
        ctor.apply(this, arguments);
    }, null, staticMembers);

This will define observable class and wraps all instance properties to be observable.


The class definition looks like:

 var Person = observableClass(function () {
}, {
    name: "Frantisek Kaduk",
    _year: 1234,
    year: {
        get: function () {
            return this._year;
    getName: function () {


 And its usage would be:

 var person = new Person();
person.bind("name", function (v) {
    WinJS.log("name has changed to " + v, "person");
}); = "Fero Kaduk";

WinJS.log("name is: " + person.getName());
WinJS.log("year is: " + person.year);


The above class definition uses more WinJS funcitonality but has again following issues:

  • all instance members are wrapped with observable functionality (including methods)
  • get/set methods doesn't work!

Running the above code generates the following output:


 person: name has changed to Frantisek Kaduk
name is: Fero Kaduk
year is: [object Object]
person: name has changed to Fero Kaduk



As we can see, getting the year doesn't work at all!


So let's see the final solution in the next post.