KnockoutJS Collections

Overview

KnockoutJS provides its own collection implementation; the ObservableArray. This collection is similar to .NET’s ObservableCollection<T> in that it allows changes to its items to be observed and acted upon.

Syntax

There are two methods of declaring a Knockout collection in HTML. The first and most popular method is to use the data-bind keyword to bind a ViewModels collection to a UL or TBODY elementA demonstration of this syntax may be observed in the simple todo example below:

Inline Declaration

<table>
<tbody data-bind=foreach:todoItems >
<tr>
<td></td>
<td><a href="#" data-bind="click: $root.removeTask">Remove</a></td>
</tr>
</tbody>
</table>

Comment Based Declaration

The second method available for declaring a KO collection in HTML is to put it in an HTML comment. This method is aesthetically elegant though may have issues for some clients due to some old proxy’s stripping comments from the HTML that is transferred over the wire. In such cases you may find that your code stops functioning correctly without easily being able to ascertain the cause. A functionally equivalent example of this method to the first method listed is shown below:

<table>
<tbody>
<!-- ko foreach: todoItems -->
<tr>
<td></td>
<td><a href="#" data-bind="click: $root.removeTask">Remove</a></td>
</tr>
<!-- /ko -->
</tbody>
</table>

Declaring the ObservableArray

The Observable array is declared in the ViewModel using the syntax shown in the sample below. This example creates a new ObservableArray, initialising it with two items:

self.todoItems = ko.observableArray([
new TodoItem("Learn the meaning of life"),
new TodoItem("Find the path to enlightenment")
]);

Observing Changes

Events are fired when the items of the array are modified. In the below example the combination of a button and textbox are included to allow a user to add items to the list. As items are added to the list the change events are fired and the table elements are selectively re-rendered on the page:

The Front-End Code

Two features are demonstrated in the below sample. Firstly the value of the textbox is bound to the current list items text. Secondly the  Add Task button is bound to the ViewModels AddItem method, which is passed the current item to be added:

<input data-bind="value: newTodoItemDescription" />
<button data-bind="click: addItem">Add Task</button>

The Back-End Code

The backend code (called by the KnockoutJS binding system by delegating the Add Tasks click event to call the ViewModels Additem function) adds a new item to the list:

// Operations
self.addItem = function() {
if(self.newTodoItemDescription() !== “”){

self.todoItems.push(new TodoItem(self.newTodoItemDescription()));
self.newTodoItemDescription(”);
}
};

Working Sample

This completes the summary of the basic points of KnockoutJS collections. View the complete working TodoList sample at my JS Bin.

Advertisements