Observable Array
ability to react to items being added or removed from an array
by Randy Crews
HTML
<script src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-2.1.0.js"></script>
<button data-bind="click: addItem">Add</button>
<button data-bind="click: removeItem">Delete</button>
<ul data-bind="template: {name: 'listTempl', foreach: list }"></ul>
<script id="listTempl" type="text/html">
<li data-bind="text: name"></li>
</script>
JavaScript
/* Observable Array methods in knockout.js
list.indexOf('value') = returne zero-based index of item
list.slice(2,4) = returns items between start and end of index value
list.push("value") = adds new item to end of array
list.pop() = removes last item of array
list.unshift("value") = insert item at beginning
list.shift() = removes first item
list.reverse() = reverses order
list.sort() = sorts the items
list.remove("item") = removes specified item
list.removeAll() = removes all items from array
*/
$(function() {
var data = [{
name: "Randy"},
{
name: "Abbey"},
{
name: "Steve"}];
var viewModel = {
list: ko.observableArray(data),
addItem: function() {
this.list.push({
name: "Frank"
});
},
removeItem: function() {
this.list.pop();
}
};
ko.applyBindings(viewModel);
});