以下设置的最佳方法是什么:项目的长列表(数百人),单击列表条目后会打开一个包含项目详细信息的新对话框。
有多个选项(另请参阅 here ):
- 使用“虚拟”模型和一个 View 并更改虚拟模型的属性 -> 不反射(reflect)对原始模型的更改
- 更改一个现有 View 的模型
- 每次点击列表时都会创建一个新 View ,这会导致模型 -> 性能问题吗?
- 使用marionette框架 -> 文档很少,这让我很难理解
- 使用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可以创建大量模型并通过单一 View 向用户展示。输入要创建的模型数量,然后单击“创建模型”。
问题:为什么会出现内存泄漏?使用模型后如何正确清理?
对于内存分配,我使用了 chrome 及其任务管理器。 70000 次浏览的内存消耗约为 30M。
最佳答案
这是我经过大量阅读和测试后找到的解决方案:
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();
}
整体 View 保持不变,所有 subview 都发生了变化。
你可以在这里找到 fiddle http://jsfiddle.net/stot/H4qPG/20/ 我创建了 1.000.000 个模型,根据 chrome 任务管理器,内存消耗在测试的很长一段时间内保持稳定。
有用信息:
关于javascript - 主干可重用 View (将新模型设置为现有 View ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21411059/