问题
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
}
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?
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.
EDIT: Here is JSFiddle of one try suggested below http://jsfiddle.net/5ScWn/ && http://jsfiddle.net/8PK6F/, but it still doesn't work.
回答1:
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
})());
}
}
};
and then use it via ko.mapping.fromJS(dataJson, mappingOptions, self.activities);
来源:https://stackoverflow.com/questions/21464454/knockout-mapping-object-array-to-observable-array-and-create-computed-property-f