如何确保正确关闭 backbone 视图

How to ensure proper closing of backbone views

我的所有视图都附有关闭功能,

Backbone.View.prototype.close = function()
{
  this.remove();
  this.unbind();

  if (this.closeMe) this.closeMe();
};

在视图中的 closeMe() 函数中,我调用了 backbone 的 off() 函数,以从模型和集合中删除先前绑定的回调函数。

closeMe: function()
   {     
     if(this.model)
        this.model.off(null, null, this);
     ...
   }

问题是,如果我在初始化函数中将一些变量附加到当前视图,我是否需要通过 closeMe() 函数处理它们?

 initialize : function(options)
    {
     ...
     this.myVar= options.something;  
    }

garbage collector 为您完成这项工作。

The garbage collector algorithm reduces the definition of "an object is not needed anymore" to "an object has no other object referencing to it". An object is considered garbage collectable if there is zero reference pointing at this object.

当对视图的引用有零引用指向它时,垃圾收集器将删除该对象。此时,如果对象myVar没有指向它的引用,垃圾收集器将删除它。

顺便说一下,我建议使用方法 listenTo 来监听事件,而不是方法 on,因为这样可以简化您的代码。当您在 Backbone 视图上调用 remove 时,从 DOM 中删除一个视图,并在视图上调用 stopListening 以删除该视图具有 listenTo 的任何绑定事件。