knockout mapping object array to observable array and create computed property foreach object

落花浮王杯 提交于 2019-12-11 14:55:46

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!