javascript 如何在可观察数组中敲除可观察对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16914629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 06:26:48  来源:igfitidea点击:

How to do Knockout observable objects inside observable array

javascriptknockout.jsknockout-2.0

提问by Chamith Malinda

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,

我想实现一个可观察的数组,并且在该数组中应该有可观察的对象(JS 对象)。在视图中,我正在迭代这个数组并获取对象并显示对象属性。假设有一个像下面这样的对象,

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

Imagine the observable array is consisting with objects like above.

想象一下 observable 数组由上面的对象组成。

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

然后我想更改特定对象的单个属性(例如名称)并需要查看视图上的更改。

How can I do this using knockout ?

我如何使用淘汰赛来做到这一点?

Thanks.

谢谢。

回答by Rune Vejen Petersen

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

如果您在 viewModel 中设置您的用户并使用敲除映射对其进行映射,您应该会得到所需的结果。就像是:

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.

这样每个映射的属性都将是一个可观察的,当它们发生变化时,这将反映在您的标记中。

回答by Damien

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

要将模型转换为可观察的视图模型,您可以使用ko.utils.arrayMapko.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

见小提琴

回答by ebram khalil

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.