当我在视图中添加卡片时,我称之为:
innerModel.addCard = function() {
// This just adds a card to the UI
var card = new cardViewModel(addCardDto);
innerModel.cards.push(card);
}.bind(this);
这会向UI添加一张空卡,并让用户输入一些信息。当他们点击“保存”时,我通过网络发送这个最小的包,保存在服务器端,然后返回一个更完整的对象。更新也是如此 - 我只发送所需内容,然后返回一个完整的对象。这是我的cardViewModel:
var cardViewModel = function(data) {
var self = this;
ko.mapping.fromJS(data, {}, this);
self.isNew = ko.observable(false);
// If the card hasn't been created yet, it won't have a cardId
if (typeof this.cardId === 'undefined') {
this.isNew(true);
}
this.save = function() {
// Implement API call here, one for POST, one for PUT. For now:
// Currently just using a hard-coded piece of data 'cardDto' that mocks the result of an API call
var result = new cardViewModel(cardDto); // Problem is somewhere around here
result.editing(false);
result.isNew(false);
debugger;
// trying to re-assign the object to the result here, but it's not working. No errors from javascript, just no activity when I click "save".
self = result;
};
};
从我的观点来看,我有:
<a data-bind="click: save">save</a>
之前我的保存方法就是这样:
this.save = function() {
// Implement API call here, one for POST, one for PUT. For now:
this.editing(false);
this.isNew(false);
};
我做错了什么?
我试过了:
this.save = function() {
// Implement API call here, one for POST, one for PUT. For now:
// Currently just using a hard-coded piece of data 'cardDto' that mocks the result of an API call
var result = new cardViewModel(cardDto); // Problem is somewhere around here
result.editing(false);
result.isNew(false);
debugger;
// trying to re-assign the object to the result here, but it's not working. No errors from javascript, just no activity when I click "save".
ko.mapping.fromJS(result, {}, self); // NEW
};
但是,当我运行它时,chrome没有任何错误或任何错误,它只是说“Aw snap”。
编辑:我在IE中运行,我得到一个“调用堆栈大小超出错误”。现在深入研究......
答案 0 :(得分:2)
self = result
将变量self
重新分配给结果,它不会导致对象更新自身或其任何属性。 self
没有什么特别的东西会改变JS赋值的工作方式。
只需致电ko.mapping.fromJS(result, {}, this)
即可更新对象。