Skip to content

Instantly share code, notes, and snippets.

@perokvist
Created October 11, 2012 07:35
Show Gist options
  • Save perokvist/3870793 to your computer and use it in GitHub Desktop.
Save perokvist/3870793 to your computer and use it in GitHub Desktop.
Two-way WinJS binding
function initializeBinding(target) {
for (var propertyName in vm) {
if (typeof vm[propertyName] !== "function" && propertyName.charAt(0) !== '_' && vm.hasOwnProperty(propertyName)) {
var selector = "input[data-win-bind='value: " + propertyName + "']";
var element = target.querySelector(selector);
if (element) {
element.addEventListener("change", onChange);
}
}
}
}
function onChange(e) {
var propName = e.target.getAttribute("data-win-bind").split(":")[1].trim();
if (!vm.hasOwnProperty(propName)) {
throw new { error: "Property '" + propName + "' was not found in view model" };
}
vm[propName] = e.target.value;
}
yourTemplateElement.winControl.render(vm, yourTargetContainer).then(function (e) {
initializeBinding(yourTargetContainer);
}
<div id="yourTemplate" data-win-control="WinJS.Binding.Template">
<input data-win-bind="value: someProperty" type="text" />
</div>
var viewModel = WinJS.Class.define(function() {
// this is the constructor function
var self = this;
}, {
// object literal for methods and attributes on the "class"
});
var observableViewModel = WinJS.Class.mix(viewModel, WinJS.Binding.mixin, WinJS.Binding.expandProperties(viewModel));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment