淘汰递归映射问题

时间:2013-03-21 09:56:45

标签: knockout.js knockout-mapping-plugin

这篇文章是对此one的跟进。

我已更新了以下代码:

viewModel.getQuotesSuccess = function (result) {

    var myCoverQuotesViewModel = function (data) {
    var self = this;
    ko.mapping.fromJS(data, {}, self);

    self.Childs = ko.observableArray(ko.utils.arrayMap(data.Childs, function (c) {
        return new myCoverQuotesViewModel(c);
    }));

    self.selectedChild = ko.observable();
    self.showChildren = ko.computed(function () {
        return self.selectedChild()
        && self.selectedChild().Childs().length > 0;
    });



var mapping = {
    'CoverQuotes': {
        create: function (options) {
            return new myCoverQuotesViewModel(options.data);
        }
    }
}

ko.mapping.fromJS(result, mapping, viewModel);

};

viewModel看起来像这样:

var viewModel = {

     CoverQuotes: [{id: 1, label:'test', Childs:[{id: 2, label:'child1'}]]
};

简而言之,我有一个CoverQuotes数组,每个元素还包含一个CoverQuotes数组(依此类推)。

我对此映射的问题是使用Childs可观察数组。致电:

 return new myCoverQuotesViewModel(options.data); 

对于主要对象,它工作正常。但是当从arrayMap函数中调用构造函数时,那一行:

 ko.mapping.fromJS(data, {}, self);

没有做任何事情。

因此,为嵌套子项分配了selectedChild和showChildren属性,但它们缺少所有其他属性(例如本例中的id和label)。

我缺少什么,所以映射也适用于儿童?

1 个答案:

答案 0 :(得分:0)

我使用递归自定义映射解决了我的问题

viewModel.getQuotesSuccess = function (result) {
    var myCoverQuotesViewModel = function (data) {
        var self = this;

        var mappingChildren = {
            'Childs': {
                create: function (options) {
                    return new myCoverQuotesViewModel(options.data);
                }
            }
        }

        ko.mapping.fromJS(data, mappingChildren, self);


        self.selectedChild = ko.observable();
        self.showChildren = ko.computed(function () {
            return self.selectedChild() && self.selectedChild().Childs().length > 0;
        });

        self.IsVisible = ko.computed({
            read: function () {
                var visible = true;
                if (self.DependsOn().length > 0) {
                    $.each(self.DependsOn(), function (index, value) {
                        var dependency = viewModel.QuoteSelectedViewModel().CoverQuotes.filterByProperty("Code", value);
                        if (dependency().length > 0) {
                            visible = visible & dependency()[0].IsSelected();
                        } else {
                            visible = false;
                        }
                    });
                }

                return visible;
            },
            deferEvaluation: true
        }, this);
    }

    var mapping = {
        'CoverQuotes': {
            create: function (options) {
                return new myCoverQuotesViewModel(options.data);
            }
        }
    }

    ko.mapping.fromJS(result, mapping, viewModel);
};