0

我正在尝试使用映射插件来使子对象的属性可观察。我有以下内容:

// setData defined here

var mapping = {

    create: function(options) {
        //customize at the root level.  
        var innerModel = ko.mapping.fromJS(options.data);
        innerModel.cardCount = ko.computed(function () {
            debugger;
            return this.cards().length;  // cards not defined - "this" is Window for some reason
        });

        innerModel.deleteCard = function (card) {
            // Pending UI
            // call API here
            // On success, complete
            this.cards.remove(card);
        }.bind(this);

        innerModel.addCard = function () {
            //debugger;
            // Pending UI
            // Call API here
            // On success, complete
            this.cards.push(dummyCard);
            //this.cardToAdd("");
        }.bind(this);

        return innerModel;
    }
};

var SetViewModel = ko.mapping.fromJS(setData, mapping);

ko.applyBindings(SetViewModel);

当我在 chrome 调试器中运行它时,我得到“对象 [对象全局] 没有方法卡”。卡片应该是一个可观察的数组。我究竟做错了什么?

4

1 回答 1

1
innerModel.cardCount = ko.computed(function () {
            debugger;
            return this.cards().length;  // cards not defined - "this" is Window for some reason
        });

this位于您正在创建的匿名函数内,因此绑定到全局对象。如果要引用内部模型,则必须直接这样做,或者将内部模型绑定到函数。

innerModel.cardCount = ko.computed(function () {
            return innerModel.cards().length; 
        });

或者

var computedFunction = function () {
            return this.cards().length; 
        };
innerModel.cardCount = ko.computed(computedFunction.apply(innerModel));
于 2013-03-24T03:30:27.623 回答