将某些observableArray对象属性转换为可观察对象 [英] Turn certain observableArray objects properties into observable
问题描述
假设我有这个相同类型对象的数组:
Say I have this array of same-type objects:
var people = [
{ status: 0, name: "name1"},
{ status: 1, name: "name2"}
];
我希望它不仅是observableArray,而且我还想要观察,例如,状态每个对象的属性。
and I want it not only to be observableArray, but also I want to observe ONLY, say, status property of each object.
想象一下,可能会添加或删除对象本身。任何这些对象的name属性都不会改变,所以我不需要观察名称,但每个对象的状态可能会被改变,因此让它可观察是很酷的。
Imagine that the objects themselves might be added or deleted. The name property of any of those objects is not going to change so I don't really need to observe the name but the status of every object might get changed, thus it'd be cool to make it observable.
是否可以使用一些很酷的黑客语法将其与knockout实用程序一起映射,或者我是否必须迭代每个对象并将其status属性映射到observable或者具有整个数组及其对象属性可观察?
Is it possible to map it with knockout utilities with some cool hack syntax or do I have to either iterate through every object and map its status property into observable or have the whole array and its objects properties observable?
推荐答案
你可以使用 ko.mapping.fromJS
var vm = ko.mapping.fromJS(people,{
create: function(options){
return {
status : ko.observable(options.data.status), // observable
name: options.data.name, // non observable
}
}
});
现在vm是一个observableArray,它包含状态是可观察的对象,而name是常规属性。
Now vm is an observableArray that contains objects in which status is an obsevable and name is a regular property.
@Patryk:
如果你有很多房产,你可以这样做并且你想只将一个转换为observable。
You could do that, if you have many properties and you want to convert only one into observable.
var o = ko.mapping.fromJS(people,{create: function(options){
// clone item
var item = ko.utils.extend(options.data, {});
// replace status property by an observable
item.status = ko.observable(options.data.status);
return item;
}});
您还可以使用观察,带有映射参数
You could also use observe with mapping parameter
var mapping = {
create: function (options) {
return ko.mapping.fromJS(options.data, {'observe': ["status"]});
}
};
var o = ko.mapping.fromJS(people, mapping);
我希望它有所帮助。
这篇关于将某些observableArray对象属性转换为可观察对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!