FreshCutDevelopment Blog

4 out of 5 dentists recommend this site

KnockoutJS Collections


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.


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

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

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:

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

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()));

Working Sample

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

What’s all this about ECMAScript 5?

ES5 is coming. With the majority of modern browsers supporting a large portion of the ES5 specification it is time to take a look at what this enhanced specification has to offer us as web developers. In large part the ES5 specification improves our ability to safely write large scale web applications by enhancing our ability to constrain what can be done with our objects at run time. As developers have moved from using JavaScript as a scripting language for adding UI widgets as an afterthought to their websites at the end of a development project, toward an increasing focus on rich client side user actions a requirement to bring safety features and constraints to the language has arisen.

Locking Down our Objects

The following features have been added to JavaScript with ES5 to allow us to lock down our objects, preventing them from being manipulated at run time when the need for this is identified:


Accessors allow us to configure various attributes of object properties such as whether the property is read only or enumerable. Full detail of what attributes are available for configuration when defining properties using accessors can be found on the Mozilla developer network. An example of when this would be useful is if you had a Person object in your application, who needed to be created with a date of birth. Of course a persons date of birth should not be modifiable after a person as been created. In this case the date of birth could be initialised into a read-only property to prevent modification for the lifetime of the application.

An example of defining a read-only property accessor with a value of 13, which may not be enumerated can be found below:

Code Sample

var o = {};

Object.defineProperty(o, "a", {value : 13,
writable : false,
enumerable : false});

Getters and Setters

JavaScript finally has getter and setter support built in. Some of the great things that  this allows us to do are as follows:

  1. The example above where we wish to constrain the date of birth for our person object to be read-only can also be achieved by defining a DateOfBirth property with a get accessor only.
  2. The functionality related to getting or setting the property values can be encapsulated.
  3. Calls to getters and setters may be intercepted by frameworks to achieve all manner of wild and wonderful things. An example of this is eventing. We could wire an event to update a related DOM element when a property value is set implementing our own basic version of the functionality that frameworks such as KnockoutJS provide.
  4. Much much more…

Code Sample

var person;

Object.defineProperty(person, "Age", {
get : function(){ return bValue; },
set : function(newValue){ bValue = newValue; }


The new Object.Seal method prevents methods/properties from being added or removed from an object at runtime. Values of properties may still be modified when an object has been sealed. This can be useful when you want to ensure that your object is used in the way that it was designed. Read more…

Code Sample

var sealedPerson = Object.seal(person);


The Object.Freeze method renders an object completely immutable. This means that no values may be modified on this object, and no properties or functions may be added or removed at run time. Immutability of objects allows developers to reason about the code that they write in ways that are not possible when objects are mutable. A later post will discuss the pros and cons of immutability in more detail.

Code Sample

var frozenPerson = Object.freeze(person);


This method provides similar benefits to the seal function in that methods may not be added to an object at runtime when extensions have been prevented. However counter sealed objects non-extendable objects may have their properties dynamically removed at runtime.

Code Sample

var nonTrainablePerson = Object.preventExtensions(person);

That sums up the overview of the ES5 offerings for locking down our objects. Still to come on further blogs are the various enhancements added to other areas of the JavaScript language.


Elevator Pitch 

KnockoutJS is an MVVM framework for the web designed to simplify the process of creating web pages with rich user interactions. This is achieved by a model binding system analogous to the way XAML based MVVM frameworks in the .NET space.

KnockoutJS Utility Belt (Tool 1) – Simple Model Binding

Knockout uses a simple template based ViewModel binding system to wire up various parts of your UI and keep them in sync. As demonstrated below:

Le Template..

<h1>Hello <data-bind="text: name"></h1>
Name:<input type="text" data-bind="value: name"/>

Le binding code…

// wires up the 'name' property of
//our ViewModel into the
//Knockout binding system
function SampleViewModel() { = ko.observable("");

// Activates knockout.js binding system
ko.applyBindings(new SampleViewModel());

The above code  specifies a template using the HTML5 ‘data-‘ attribute to create a binding to the name property of the ViewModel defined at the end of the code snippet. Updating a value in the text box causes a corresponding update in the heading text. This is a toy example of Knockouts model binding capabilities. Coming tutorials will delve into the inner workings of the binding system and flex them in a more compelling set of scenarios.

Getting a start in blogging

A recent post by Scott Hanselman has finally convinced me that I need to get a start in the pursuit of blogging. The aim of this blog is to provide an online source of information on technological topics along with other miscellaneous endeavours.

I will try to post a brief overview of each new topic that I learn. The aim of this is two fold, firstly to provide a short overview on the various topics covered to readers, and secondly to save the information for future referral.

That brings the first post to an ending point. We’ll see whether the initial momentum can be maintained…