If you’re a web developer with prior experience from MVVM/MV* frameworks like Knockout or Batman going into Windows 8 development, one thing you quickly notice is the lack of two-way binding when using the WinJS template control.
In this blog post we´re going to show you a starting point to roll your own two-way binding without going to another lib, when binding a simple view model to a view with a WinJS template.
When working with the ListView control you have been introduced to the concept of data sources, like the WinJS.Binding.List. The binding list used to make an array into an observable object for the control.
For the view model, the first thing would be to set up the observable behavior for one-way binding. Luckily there is some mixins that we could use to achieve this.
Now that would enable us to have an ordinary WinJS template with one-way binding for our view model.
To render the template we pass the view model and a target element where the template should be added.
We now bind our view model to this template with an imaginary “someProperty”. Changes of the “someProperty” should be reflected in the template. It is the other way around that is interesting to us in this case, to achieve two-way binding.
To do this we´re going to use the binding attribute in the template. We´re looping through the view models properties, to find a matching binding. Then we´re going to hook up the change event of that element to update the view model .
This does the basic trick. Now the change event of the input is hooked up to update to corresponding property on the view model.
We now have a basic structure to get two-way binding in simple scenarios based on inputs. This could be continued to support more scenarios, but the point was to show a possible solution to two-way binding. Of course you could in many cases use your favorite framework for your templating and binding needs.