Knockout with jQuery
by aaronaudic
HTML
<script src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-2.2.1.js"></script>
Name:
<input type="text" data-bind="value: name, valueUpdate: 'afterkeydown'" />
<input type="checkbox" data-bind="checked: nameVisible" />
<p>Hello, <span data-bind="text: name, visible:nameVisible"></span>
<br/> <span data-bind="text: displayName"></span>
</p>
<button data-bind="click: changeName">Change Name</button>
<br/>
<button data-bind="click: addItem">Add</button>
<button data-bind="click: removeItem">Remove</button>
<ul data-bind="template: {name: 'listTemplate', foreach: list}"></ul>
<script id="listTemplate" type="text/html">
<li data-bind="text: name"></li>
</script>
JavaScript
$(function () {
var viewModel = {
name: ko.observable("Aaron"),
changeName: function () {
this.name("Kendra");
},
nameVisible: ko.observable(true),
var data = [{name: "Aaron"}, {name: "Kendra"}];
list: ko.observableArray(data)
addItem: function(){
this.list.push({name: "Steve"});
}
removeItem: function(){
this.list.pop();
}
};
viewModel.displayName = ko.computed(function () {
return this.name() + " is " + (!this.nameVisible() ? "not" : "") + " visible.";
}, viewModel);
ko.applyBindings(viewModel);
});