How to do Knockout observable objects inside observable array

Chamith Malinda picture Chamith Malinda · Jun 4, 2013 · Viewed 15.5k times · Source

I want to implement an observable array and inside that array there should be observable objects (JS object). And In the view I'm iterating this array and getting the object and show the object properties. Let say there is a object like following,

{"name":"john","age":21,"address":"No 25"}

Imagine the observable array is consisting with objects like above.

Then I want to change single property (e.g name) of a particular object and need to see the change on the view.

How can I do this using knockout ?

Thanks.

Answer

Rune Vejen Petersen picture Rune Vejen Petersen · Jun 4, 2013

If you set up your users in a viewModel and map it with knockout mapping you should get the desired result. Something like:

myObservableArray.push(new UserViewModel( {"name":"john","age":21,"address":"No 25"} ));  

var UserViewModel = function(data){
    var self = this;
    ko.mapping.fromJS(data, {}, self);    
}

This way each of the mapped properties will be an observable and when they change, this will be reflected in your markup.