正在清除主干模型/集合内存泄漏

Clearing backbone model/collection memory leaks

本文关键字:集合 内存 泄漏 模型 清除      更新时间:2023-09-26

尝试使用Chrome中的堆快照工具来处理Backbone的内存管理。视图上有一个后退按钮,单击后将通过主干路由器将当前视图切换为新视图。

我在初始页面上拍摄快照,用后退按钮导航到页面,单击后退按钮并拍摄另一个快照。使用comparison选项,我希望堆快照是相同的。然而,旧模型/集合似乎没有被清除(它们在快照中以白色突出显示,即仍然可以通过图的根访问)。此外,看起来视图本身也没有被删除(快照中的白色高亮显示相同)。

我链接了一张图表来帮助解释(https://i.stack.imgur.com/mlN2I.jpg)。假设视图V1嵌套三个视图,其中V2包含模型M1,V3包含模型M2,V4包含主干集合C1。M1监听对M2的改变并相应地更新其自身。为了正确删除视图V1,需要执行以下操作:

  • 对V1及其所有子视图(以及这些子视图的子视图(如果存在))调用Backbone.View.Remove
  • 对所有模型(以及这些模型的子模型(如果存在))调用Backbone.Events.StopListening

这足以彻底澄清观点吗?似乎大多数在线资源都在讨论主干视图的正确处理,但没有讨论其模型/集合。

任何帮助都将不胜感激。谢谢

使用此方法从内存中清除子视图和当前视图

//FIRST EXTEND THE BACKBONE VIEW....
//Extending the backbone view...
Backbone.View.prototype.destroy_view = function()
{ 
   //for doing something before closing.....
   if (this.beforeClose) {
       this.beforeClose();
   }
   //For destroying the related child views...
   if (this.destroyChild)
   {
       this.destroyChild();
   }
   this.undelegateEvents();
   $(this.el).removeData().unbind(); 
  //Remove view from DOM
  this.remove();  
  Backbone.View.prototype.remove.call(this);
 }

//Function for destroying the child views...
Backbone.View.prototype.destroyChild  = function(){
   console.info("Closing the child views...");
   //Remember to push the child views of a parent view using this.childViews
   if(this.childViews){
      var len = this.childViews.length;
      for(var i=0; i<len; i++){
         this.childViews[i].destroy_view();
      }
   }//End of if statement
} //End of destroyChild function

//Now extending the Router ..
var Test_Routers = Backbone.Router.extend({
   //Always call this function before calling a route call function...
   closePreviousViews: function() {
       console.log("Closing the pervious in memory views...");
       if (this.currentView)
           this.currentView.destroy_view();
   },
   routes:{
       "test"    :  "testRoute"
   },
   testRoute: function(){
       //Always call this method before calling the route..
       this.closePreviousViews();
       .....
   }

   //Now calling the views...
   $(document).ready(function(e) {
      var Router = new Test_Routers();
      Backbone.history.start({root: "/"}); 
   });

  //Now showing how to push child views in parent views and setting of current views...
  var Test_View = Backbone.View.extend({
       initialize:function(){
          //Now setting the current view..
          Router.currentView = this;
         //If your views contains child views then first initialize...
         this.childViews = [];
         //Now push any child views you create in this parent view. 
         //It will automatically get deleted
         //this.childViews.push(childView);
       }
  });

类似的问题已经有了一些答案。

这里的旧答案和一个有点新鲜的答案,即使有视频