Skip to content Skip to sidebar Skip to footer

How To Update Observable Array Element In Knockoutjs?

I have following JavaScript array, [{'unitPrice': 2499,'currency':'$','productId':1,'retailerId':1,'productName':'XX ','formattedPrice':'$ 2,499','productImage':'Images/2012_08_12_

Solution 1:

The above behavior is because only the array is an observable and not the individual elements within the array or the properties of each element.

When you do item.productQuantity = 20;, this will update the property but since it is not an observable, the UI does not get updated.

Similary, item.productQuantity(20) gives you an error because productQuantity is not an observable.

You should look at defining the object structure for each element of your array and then add elements of that type to your observable array. Once this is done, you will be able to do something like item.productQuantity(20) and the UI will update itself immediately.

EDIT Added the function provided by the OP :). This function will convert each property of the elements in an array to observables.

functionconvertToObservable(list) 
{ 
    var newList = []; 
    $.each(list, function (i, obj) {
        var newObj = {}; 
        Object.keys(obj).forEach(function (key) { 
            newObj[key] = ko.observable(obj[key]); 
        }); 
        newList.push(newObj); 
    }); 
    return newList; 
}

END EDIT

If you are unable to change that piece of code, you can also do something like observableItems.valueHasMutated(). However, this is not a good thing to do as it signals to KO and your UI that the whole array has changed and the UI will render the whole array based on the bindings.

Solution 2:

You can easily use ko.mapping plugin to convert object to become observable: http://knockoutjs.com/documentation/plugins-mapping.html

Convert regular JS entity to observable entity:

var viewModel = ko.mapping.fromJS(data);

Convert observable object to regular JS object:

var unmapped = ko.mapping.toJS(viewModel);

Post a Comment for "How To Update Observable Array Element In Knockoutjs?"