Skip to content

Instantly share code, notes, and snippets.

@markrendle
Created June 4, 2012 12:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markrendle/2867979 to your computer and use it in GitHub Desktop.
Save markrendle/2867979 to your computer and use it in GitHub Desktop.
Knockout ViewModel from WinRT object
// Reusable Knockout ViewModel from WinRT object
// with two-way binding enabled.
(function () {
function camelCase(str) {
return str[0].toLowerCase() + str.substring(1);
}
function makeViewModel(obj) {
var vm = {};
var properties = Object.keys(Object.getPrototypeOf(obj));
properties.forEach(function (p) {
if (typeof obj[p] !== "function") {
vm[p] = ko.observable(obj[p]);
vm[p].subscribe(function (newValue) {
obj[p] = newValue;
});
}
});
// The WinRT object needs to expose a "Changed" event.
// INotifyPropertyChanged.PropertyChanged does not work for some reason.
obj.addEventListener("changed", function (e) {
var p = camelCase(e.propertyName);
vm[p](obj[p]);
});
return vm;
}
WinJS.Namespace.define("KnockoutRT", { makeViewModel: makeViewModel });
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment