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を参照する場合は、直接参照するか、innermodelを関数にバインドする必要があります。

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 に答える