Billa
Billa

Reputation: 5266

Knockout ObservableArray not getting updated in UI

I am trying to update the array value bound to ObservaleArray. However its not getting updated.

function AppViewModel() {
    var self = this;
    self.Title=ko.observable('Sample');
    self.people = ko.observableArray([
         new Person('Ajay'),
         new Person('Kumar')
    ]);

    self.updateAns=function(){
     self.people()[0].Answered=false;
    };

    self.updateName=function(){
     self.people()[0].Name('John');
    };
    self.updateTitle=function(){
     self.Title('New Title');
    };

}

var Person=function(name){
  this.Name=name;
  this.Answer=[{Id: 1, Answered:true},{Id:2, Answered:true}]
}

ko.applyBindings(new AppViewModel());

Full Demo

How to keep the array value sync?

Upvotes: 0

Views: 56

Answers (2)

Max Brodin
Max Brodin

Reputation: 3938

Observable array tracks changes of a collection of things. Meaning it doesn't detect changes of array items, but only changes of the collection, like add/remove/replace elements. In order to keep Person name value in sync it should be observable.

var Person = function(name){
  this.Name = ko.observable(name);
  ...
}

Updated demo

Upvotes: 1

Anders
Anders

Reputation: 17554

The observable array will only listen to changes to the array itself, you also need the members onthe Person to be observables if you want them to update

Upvotes: 1

Related Questions