剔除将对象数组映射到可观察数组,并为每个对象创建计算属性 [英] knockout mapping object array to observable array and create computed property foreach object
问题描述
我想通过以下方式将json数组数据映射到observablearray:
I want to map a json array data to observablearray in the following way:
var modell = function() {
self.activities = ko.observableArray();
...
ko.mapping.fromJS(dataJson, {}, self.activities);
// as a result I can use self.activities[0].FirstName or other properties
}
每个活动都是复杂的对象.
为简单起见,我们可以假设每个活动中都有两个属性-FirstName
和LastName
.这很好用,但是有可能写
映射选项将为每个活动创建计算的可观察的FullName
?
Each activity is complex object.
For simplicity, we can assume that there are two properties within each activity - FirstName
and LastName
. This works nice, but is it possible to write
mapping options that will create computed observable FullName
for each activity?
因此,我需要引用self.activities [0] .FirstName以及self.activities [0] .FullName,其中FirstName很容易观察到,但FullName是计算得出的.
So, I need to reference like self.activities[0].FirstName, as well as self.activities[0].FullName, where FirstName is simple observable, but FullName is computed.
这是JSFiddle在 http://jsfiddle.net/5ScWn/下面建议的一种尝试. http://jsfiddle.net/8PK6F/,但仍然无法正常工作.
Here is JSFiddle of one try suggested below http://jsfiddle.net/5ScWn/ && http://jsfiddle.net/8PK6F/, but it still doesn't work.
推荐答案
是的,可以使用映射选项为可观察数组中的每个项目创建计算的可观察对象.请尝试以下操作:
Yes, it is possible to use mapping options that will create computed observable(s) for each item in an observable array. Try the following:
var mappingOptions = {
'activities': {
create: function (options) {
return (new (function () {
this.fullName = ko.computed(function () {
return this.firstName() + ' ' + this.lastName;
}, this);
ko.mapping.fromJS(options.data, {}, this); // continue the std mapping
})());
}
}
};
,然后通过ko.mapping.fromJS(dataJson, mappingOptions, self.activities);
这篇关于剔除将对象数组映射到可观察数组,并为每个对象创建计算属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!