Tuesday, November 5, 2013

Utility function to make an array observable in knockoutjs

Suppose we have an array

var employees = [
    { EmployeeID: 1, EmployeeName: "Naveen" },
    { EmployeeID: 2, EmployeeName: "Shebin" }

We can make it an observable array by calling it like this

var observableEmployees = ko.observableArray( employees );
But as per knockoutjs documentation,

Simply putting an object into an observableArray doesn’t make all of that object’s properties themselves observable. Of course, you can make those properties observable if you wish, but that’s an independent choice. An observableArray just tracks which objects it holds, and notifies listeners when objects are added or removed.

 This means that any change in array will be remembered. ie, adding and removing elements in an array is observed. But changes to properties are not remembered. That is if employee[0].EmployeeName is changed to Noah, it wont be remembered. To do that we have to make each property ko.observable. Here is a small utility function to do so.

function MakeArrayKoObservableObjectArray(arr) {
    var observableArr = [];
    for (var i = 0; i < arr.length; i++) {
        var observableObj = {}, obj = arr[i];
        for (var prop in obj) {
            if (obj.hasOwnProperty(prop)) {
                observableObj[prop] = ko.observable(obj[prop]);
    return observableArr;
Now we can call it like this.

employees = MakeArrayKoObservableObjectArray( employees  );
var observableEmployees = ko.observableArray( employees );

Happy Coding!

Related Posts :

0 comments on "Utility function to make an array observable in knockoutjs"

Add your comment. Please don't spam!
Subscribe in a Reader

Post a Comment