在视图中,我在从模型内的集合中删除项目时遇到一些问题。基本上模型/集合结构如下:
基本上,当我尝试从子项目视图中的子项目集合中删除项目时,它实际上会从集合中删除正确的项目。然而,当我坚持主模型时,该项目似乎仍在集合中。
这就是我的观点的结构:
主视图插入主模型所需的 DOM 节点,主模型为项目模型等创建一个新视图。所有视图都将主模型作为模型选项,如下所示:
new App.Views.MainModelView({
model : this.model,
el : $('#nodeID')
})
唯一的区别在于子项目模型视图的创建,其中,由于视图和模板的可重用性,我仍然传入主模型,但是我还传入当前正在创建的项目集合中的项目。修改的。看起来像这样:
new App.Views.ItemView({
model : this.model,
item : this.selectedItem,
el : $('#nodeID')
});
在子项的视图 init 方法中,我执行以下操作:
this.item = (this.options.item) ? this.options.item : this.model;
要从子项目集合中删除子项目,我会执行以下操作:
removeSubItem : function(e) {
// get the id of the sub-item to be removed
var id = $(e.target).closest('tr').attr('data-id');
if (!id) throw "Could not retrieve data id";
// retrieve the sub-item from the collection
var subItem = this.item.subItems.get(id);
// remove the sub-item from the collection
this.item.subItems.remove(subItem);
},
正如我之前所说,当我删除子项并检查视图修改的集合时,我可以看到子项已从集合中删除,但是随后我保留主模型,删除的子项重新出现。这让我相信,在某个地方,子项目集合可能会被克隆,这可以解释子项目突然重新出现的原因。
我知道这是一个相当具体的问题,我不确定是否可以通过我在这里提供的内容找到问题的原因,如果您需要更多信息,请告诉我。
感谢你的帮助,
Vincent
========== 编辑 ============
为了回答下面的一些问题,让我概述一下我遇到此问题的范围:
如果我在 SubItem 视图中控制台记录 this.item.subItems 集合,则在调用 removeSubItem 后,我可以看到 SubItem 模型的实例已成功删除。
在主模型上调用 save 方法之前,我通过控制台记录 toJSON 函数的返回。此时,我遇到了先前删除的实例“返回”到集合中的问题。我一直在使用 Wireshark 和 Google Chrome 的开发者控制台监控客户端和服务器之间的流量,并且没有调用服务器来刷新任何模型。
SubItem 集合的 toJSON 方法如下所示:
toJSON : function() {
App.log(["SubItem::collection::toJSON", this], "info");
var json = {};
// make sure the key for each SubItem is the primary key
this.each(function(subItem) {
json[subItem.get('id')] = subItem.toJSON();
});
return json;
}