KnockoutJS: UI does not update when using observableArray

It seems this is a common mistake when working with KnockoutJS. Developers, myself included, have spent plenty of time scratching our heads over why a drop-down, or other list-based page element, doesn’t dynamically update when items are pushed into an observableArray.

When you’re regularly working with observables, you get into a habit of calling the observable to set a  value.

// Define an observable
var myObsrvable = ko.observable();

// Make the value change on the page
myObservable(‘some value’);

So when working with an observableArray, you could be forgiven for automatically doing the same.

// Define an observableArray
var myList = ko.observableArray();
 
// This does not update the UI
myList().push(‘some value’);

Why doesn’t this work? The reason is because calling myList() returns the underlying array, and knockout doesn’t see “some value” being pushed in.

The correct way is to use the push method on the observableArray itself which ensures knockout gets notified of the addition.

// The UI now updates
myList.push(‘some value’)

As well as push(), an observableArray provides a number of other array-like functions, such as pop() and splice() – see http://knockoutjs.com/documentation/observableArrays.html for further details.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s