Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do Knockout observable objects inside observable array

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.

like image 683
Chamith Malinda Avatar asked Jun 04 '13 09:06

Chamith Malinda


People also ask

What is Ko observable ()?

An observable is useful in various scenarios where we are displaying or editing multiple values and require repeated sections of the UI to appear and disappear as items are inserted and deleted. The main advantage of KO is that it updates our UI automatically when the view model changes.


1 Answers

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.

like image 67
Rune Vejen Petersen Avatar answered Oct 22 '22 20:10

Rune Vejen Petersen