Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating an observableArray does not update UI

I am using the containerless flow control in ko 2.0. When I update an item in my observableArray it is not updating the UI. I am updating the array like this:

this.editFormHost = function (formHost) {
    ...
    formHost.HostName = newHostName;
    this.formHosts[index] = formHost;
}

I am thinking it doesn't update because updating the array by index does not call anything in ko. From looking at the documentation it looks like there are no methods to update an object which will in turn update the UI. Or is there?

like image 573
Rush Frisby Avatar asked Jan 14 '12 08:01

Rush Frisby


1 Answers

Here is a a fiddle that demonstrates how to replace an item in an observableArray and have its changes notify the UI.

http://jsfiddle.net/johnpapa/ckMJE/

The key here is the replace function on the observableArray. You could also use splice.

... Notice the use of "replace" below ...

var ViewModel = function() {
    this.self = this;
    self.index = ko.observable(0); // default
    self.newColor = ko.observable("purple"); // default
    self.colors = ko.observableArray([{
        color: 'red'},
    {
        color: 'blue'},
    {
        color: 'yellow'}]);
    self.replaceIt = function() {
        self.colors.replace(self.colors()[self.index()], {
            color: self.newColor()
        });
    };
};
ko.applyBindings(new ViewModel());
like image 198
John Papa Avatar answered Sep 28 '22 09:09

John Papa