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
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
observableArray provides a number of other array-like functions, such as
splice() – see http://knockoutjs.com/documentation/observableArrays.html for further details.