Rudimentary Way to Make a WinRT Component Object Bindable in WinJS

When projecting a WinRT Component object to WinJS, I kept running into an exception saying that the WinRT object could not be extended. This post will briefly describe how I got around this issue.

There are a few things known that helped come to this solution:

  • I didn’t need to worry about differences between one-way/two-way binding. All I had to do was present the object onto the screen.
  • Average JavaScript objects are bindable with WinJS
  • JavaScript objects are essentially associative arrays
  • If a member does not exist when referenced in an assignment operation, it is first created, then assigned.
  • I can essentially “clone” objects by iteratively copying members using array syntax.

This last item is exactly what I did! Let me elaborate: It is simple. At this point, we can’t bind to WinRT Objects therefore we need to make them bindable ourselves. The code snippet below shows this.

function _makeBindable(obj) {
  var o = new Object();
  for (m in obj) {
    o[m] = obj[m];
  }
  return o;
}
var winrtObj = Projection.getWinRTObject();
// cannot bind winrtObj
var bindableWinRTObj = _makeBindable(winrtObj);
// use bindableWinRTObj for data-binding scenarios

Lets look at _makeBindable in a little more detail.

First, the function takes an object as a parameter. This object is the WinRT object that is causing issues. Then, a local variable is created assigned to a new Object.

The next part is very important – iterating over the members of the WinRT object. Using a for-in loop, cloning an object is quite easy. In this case, “m” represents the current member name as a string. Since JavaScript objects are essentially associative arrays, “m” can be used to access the current WinRT object’s member using array syntax. The member name is also used to assign to the local variable that was previously created. This effectively copied the current member from the WinRT object to the local variable.

Once all of the members are copied, the local variable is returned for use in data-binding scenarios.