Reputation: 507
I am new to Knockout and my requirement is,whenever an object property of an observable array changes its value programmatically, the UI should update accordingly. But it doesn't seems to work for me.
I am aware that, for this to work the object property needs to be an observable itself. And I am making it observable, but somehow its not updating UI. I tried same on normal field of a model and it works.
Can anyone please suggest on what I am missing ?
var appViewModel = function() {
this.firstName = ko.observable("Amit");
this.Books = ko.observableArray(Books);
this.updateBook = function() {
this.Books()[0].Book = ko.observable(this.Books()[0].Book);
this.firstName("Goda");
this.Books()[0].Book("Harry Potter and Prisoner of Azkaban");
}
};
I have my complete code here
Upvotes: 1
Views: 464
Reputation: 15053
You're trying to make the book observable after you've bound the data.
You want to recursively make Books
observable. This can be done with the mapping plugin:
this.Books = ko.mapping.fromJS(Books);
This way you can simply do the following in updateBook
:
this.firstName("Goda");
this.Books()[0].Book("Harry Potter and Prisoner of Azkaban");
See: http://jsfiddle.net/jVQY8/1/
Edit:
To revert the changes you could simple keep track of the original data:
var initialData = Books;
Then use the mapping plugin again to revert the changes:
self.revert = function() {
ko.mapping.fromJS(initialData, self.Books);
};
See: http://jsfiddle.net/jVQY8/2/
For a more advanced solution where you can commit / reset the value, see the following post: http://www.knockmeout.net/2011/03/guard-your-model-accept-or-cancel-edits.html
Upvotes: 1