我正在尝试使用映射插件来使子对象的属性可观察。我有以下内容:
// 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调试器中运行它时,我得到“Object [Object global]没有方法卡”。卡应该是一个可观察的数组。我究竟做错了什么?
答案 0 :(得分: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));