Created
June 4, 2012 12:14
-
-
Save markrendle/2867979 to your computer and use it in GitHub Desktop.
Knockout ViewModel from WinRT object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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