javascript - Backbone Marionette - 布局 View 僵尸

标签 javascript backbone.js memory-leaks marionette

我的 Backbone Marionette 应用程序出现问题,我的 subview 没有被完全破坏。您如何正确销毁要替换为另一个布局/项目 View 的嵌套布局 View ?

我对 Marionette documentation on destroying layout views 印象深刻,当我设置一个区域来显示新 View 时,旧 View 被破坏。但是,通过 vent 触发的事件仍然对据称已被破坏的旧 View 可见。

我在这里创建了这个问题的示例:https://jsfiddle.net/dhardin/5j3x2unx/

我认为问题出在我的路由器上:

App.Router = Marionette.AppRouter.extend({
  routes: {
    '': 'showView1',
    'view1': 'showView1',
    'view2': 'showView2'

  },
  showView1: function() {
    var view1 = new App.View1();
    App.Layout.mainRegion.empty();
    App.Layout.mainRegion.show(view1);
  },
  showView2: function() {
    var view2 = new App.View2();
    App.Layout.mainRegion.empty();
    App.Layout.mainRegion.show(view2);
  }
});

根据我的理解,App.Layout.mainRegion.empty() 不是必需的,因为在区域管理器中销毁 View 时会处理此问题 显示() 功能。 要查看问题,请通过导航导航到另一个 View ,然后单击按钮。您将看到针对旧 View 和新 View 都触发了警报。

回到我的 pre-marionette 应用程序中,我遵循了一种清理模式来避免讨论的这些内存泄漏 here .

本质上,当我的应用更改为新 View 时,我显示的 View 会调用以下函数:

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

如果您需要任何其他信息,请告诉我。提前致谢!

最佳答案

对于此类情况,您应该利用 onDestroy 函数来执行超出 Marionette 提供的额外清理工作。当 View 被替换或删除时,Marionette 会自动调用 onDestroy

onDestroy: function() {
     App.vent.off('ButtonClicked', this.onButtonClicked, this);
  }

来自 Marionette 文档:

By providing an onDestroy method in your view definition, you can run custom code for your view that is fired after your view has been destroyed and cleaned up. The onDestroy method will be passed any arguments that destroy was invoked with. This lets you handle any additional clean up code without having to override the destroy method.

在这里查看工作 fiddle :https://jsfiddle.net/ocfn574a/

请注意,我确实更新了您的路由配置中的拼写错误:'showVeiw1' -> 'showView1'

关于javascript - Backbone Marionette - 布局 View 僵尸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37213561/

相关文章:

ios - 与 Deinit 和内存泄漏混淆

javascript - 未处理的拒绝(TypeError): this. setState 不是函数

javascript - Google Apps 脚本无法为一行中的值编制索引

javascript - 使用 AnythingSlider 滑动背景

javascript - each() 函数未在 this.collection 上定义

c++ - memset 在模板类构造函数中泄漏内存

.net - 诊断.NET中的内存泄漏的工具(ASP.NET应用程序)

javascript - 获取 Javascript JSON 字符串中的参数值?

ruby-on-rails-3 - 如何使用phonegap和devise完成登录(Rails)

backbone.js - 绑定(bind)时触发的 Backbone 事件