How to do Knockout observable objects inside observable array
Asked Answered
U

3

11

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.

Uranalysis answered 4/6, 2013 at 9:46 Comment(0)
L
9

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.

Lorylose answered 4/6, 2013 at 10:13 Comment(2)
As of now, the plugin referenced in the answer seems to abandoned.Neville
It still works with the latest version of Knockout (3.4.0)Lorylose
A
2

To convert model into an observable view model, you can use ko.utils.arrayMap and ko.mapping.fromJS.

var source = [{"name":"john","age":21,"address":"No 25"}];
var vm = ko.utils.arrayMap(source, function (item) {
    return  ko.mapping.fromJS(item)
});

See fiddle

Amandy answered 4/6, 2013 at 11:17 Comment(0)
I
2

Simply define a new model for your data items and make each property observable, like this:

var dataItemModel = function (name, age, address) {
    this.name = ko.observable(name);
    this.age = ko.observable(age);
    this.address = ko.observable(address);
}

When you get your data, loop over them, create your dataItemModel(which has observable properties) and then add this item to your ObservableArray.

Impi answered 4/6, 2013 at 11:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.