2
在我的应用程序中,我有两个视图共享相同模型的情况。从集合中删除模型将删除视图的参考
我在通过模型访问集合并从集合中删除模型时遇到了问题。问题是在调用this.model.collection.remove(this.model)
后,视图的参考this.model
未定义。
我不是在删除事件前解除绑定的原因是,我需要mySecondView
才能知道删除事件,以便从DOM中删除它。
MyView = Backbone.View.extend({
events : {
'click .delete' : deleteModel
}
initialize : function() {
this.model.on('remove', this.dispose, this)
},
deleteModel : function() {
if(this.model.isNew())
{
this.model.collection.remove(this.model);
//remove all the events bound to the model
this.model.unbind(); //this.model is undefined
this.dispose();
}
}
});
MySecondView = Backbone.View.extend({
initialize : function() {
//call the custom dispose method to remove the view
this.model.on('remove', this.dispose, this);
}
});
myModel = new Backbone.Model();
myCollection = new Backbone.Collection(myModel);
myView = new MyView({ model : myModel });
mySecondView = new MySecondView({ model : myModel });
唯一可行的方法是通过创建一个局部变量参考模型deleteModel
有什么建议?
当你[销毁](http://documentcloud.github.com/backbone/#Model-destroy)一个模型时,它会触发一个'destroy'事件,该事件冒泡到集合中,所以你不需要调用' this.model.collection.remove(this.model);' – Jack
这是一个新的模型,它不存在于服务器上,只需要在客户端删除。我有一个打字错误,我修正了我调用'this.destroy'而不是'this.dispose'的地方。 – Daniel