【问题标题】:Backbone reusable view (set new model to existing view)骨干可重用视图(将新模型设置为现有视图)
【发布时间】:2014-02-20 01:46:49
【问题描述】:

以下设置的最佳方法是什么:如果项目(数百人)的长列表,单击列表条目后会打开一个包含项目详细信息的新对话框。

有几个选项(另见here):

  1. 使用“虚拟”模型和一个视图并更改虚拟模型的属性 -> 不反映对原始模型的更改
  2. 更改现有视图的模型
  3. 每次单击列表时都会创建一个新视图,这会导致模型 -> 性能问题?
  4. 使用 marionette 框架 -> 文档很少,我很难理解
  5. 使用JSPerf查看 -> 我尝试了在线演示,但在快速滚动时出现了几个错误

我尝试了选项 2,但似乎存在内存泄漏。

ReusableView = Backbone.View.extend({
    setModel: function( model) {
        // unbind all events
        this.model.stopListening();        
        this.undelegateEvents();

        // set new model
        this.model = model;
        this.delegateEvents({
            "click": "onClicked",
            "mouseover": "onMouseOver"
        });
        this.initialize();
    }          
});

这是一个fiddle,可以创建许多模型,并通过一个视图向用户展示。输入要创建的模型数量,然后单击创建模型。

问题:为什么会出现内存泄漏?使用模型后如何正确清理?

对于内存分配,我使用了 chrome 及其任务管理器。 70000 次观看需要大约 30M 的内存。

【问题讨论】:

  • 您只需调用this.delegateEvents(),它就会从您的事件哈希中提取它们。

标签: javascript backbone.js view model


【解决方案1】:

这是我经过大量阅读和测试后想出的解决方案:

setModel: function( model) {
    // unbind all view related things
    this.$el.children().removeData().unbind();
    this.$el.children().remove();
    this.stopListening();

    // clear model
    if ( this.model) {
        this.model.unbind();
        this.model.stopListening();        
    }

    // set new model and call initialize
    this.model = model;
    this.delegateEvents( this.events);    // will call undelegateEvents internally      
    this.initialize();
}   

整体视图保持不变,所有孩子都改变了。

你可以在这里找到小提琴http://jsfiddle.net/stot/H4qPG/20/ 我创建了 1.000.000 个模型,根据 chrome 任务管理器,内存消耗在这个测试的很长一段时间内是稳定的。

有用的信息:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-26
    • 2016-01-23
    • 1970-01-01
    • 2013-01-14
    • 1970-01-01
    • 2015-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多