销毁或删除Backbone.js中的视图

我目前正在尝试实施视图的销毁/删除方法,但我不能得到一个通用的解决scheme,为我所有的意见工作。

我希望有一个事件附加到控制器,以便当一个新的请求通过它破坏以前的意见, 然后加载新的。

有没有办法做到这一点,而不必build立每个视图的删除function?

不知道所有的信息…您可以将重置触发器绑定到您的模型或控制器:

this.bind("reset", this.updateView); 

当你想重置视图时,触发重置。

对于您的callback,请执行以下操作:

 updateView: function() { view.remove(); view.render(); }; 

我必须绝对确信这个观点不仅仅是从DOM中移除,而且完全不受事件的束缚。

 destroy_view: function() { // COMPLETELY UNBIND THE VIEW this.undelegateEvents(); this.$el.removeData().unbind(); // Remove view from DOM this.remove(); Backbone.View.prototype.remove.call(this); } 

似乎对我来说过分杀伤,但其他方法并没有完全做到这一点。

我知道我迟到了,但希望这会对别人有用。 如果您正在使用backbone v0.9.9 +,则可以使用listenTostopListening

 initialize: function () { this.listenTo(this.model, 'change', this.render); this.listenTo(this.model, 'destroy', this.remove); } 

stopListening通过remove自动调用。 你可以在这里和这里阅读更多

这是我一直在使用的。 没有看到任何问题。

 destroy: function(){ this.remove(); this.unbind(); } 

根据目前的骨干文件….

view.remove()

从DOM中删除一个视图和它的el,并调用stopListening去除视图已经listenTo'd的任何绑定的事件。

我认为这应该工作

 destroyView : function () { this.$el.remove(); } 

你可以用这种方式来解决问题!

 initialize:function(){ this.trigger('remove-compnents-cart'); var _this = this; Backbone.View.prototype.on('remove-compnents-cart',function(){ //Backbone.View.prototype.remove; Backbone.View.prototype.off(); _this.undelegateEvents(); }) } 

另一种方法:创build一个全局variables,如下所示: _global.routerList

 initialize:function(){ this.routerName = 'home'; _global.routerList.push(this); } /*remove it in memory*/ for (var i=0;i<_global.routerList.length;i++){ Backbone.View.prototype.remove.call(_global.routerList[i]); }