[英]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). 我想实现一个可观察的数组,在该数组中应该有可观察的对象(JS对象)。 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. 如果您在viewModel中设置用户并使用knockout映射映射它,您应该获得所需的结果。 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 . 要将模型转换为可观察的视图模型,可以使用ko.utils.arrayMap和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)
});
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
. 获取数据后,循环遍历它们,创建
dataItemModel
(具有可观察的属性),然后将此项添加到ObservableArray
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.