简体   繁体   中英

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 (eg name) of a particular object and need to see the change on the view.

How can I do this using knockout ?

Thanks.

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.

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM