这是我参与过的项目的简化示例。
一切正常但由于某种原因内存使用量增加,一些元素不会从DOM中删除。
我已经阅读了很多关于Backbone内存泄漏的文章,但它没有帮助。
我正在使用Backbone.stickit来建模绑定,我认为这会导致问题。
如何修复此代码以获得最佳内存性能?查看jsbin上的示例代码和vimeo
上的效果测试视频<!DOCTYPE html>
<html>
<head>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/backbone.stickit/0.8.0/backbone.stickit.min.js"></script>
<script src="main.js"></script>
<meta charset="utf-8">
<title>test</title>
</head>
<body>
<div id="Menu"></div>
<ol id="Items"></ol>
<div id="main"></div>
</body>
</html>
var Data = Backbone.Model.extend({
defaults: {
title: "Default Title"
},
});
var ItemForm = Backbone.View.extend({
template: _.template("<p>Your title: <%= title %></p><input name='title' value=<%= title %> /> <button name='close'>Close</button>"),
events: {
'click [name=close]':'closeEditForm'
},
bindings: {
'input[name=title]': {
observe: 'title',
events: ['blur']
}
},
initialize: function () {
this.listenTo(this.model,'change',this.render);
},
render: function() {
this.$el.html( this.template( this.model.toJSON() ) );
this.stickit();
return this;
},
closeEditForm: function () {
// this.undelegateEvents();
this.unstickit();
this.remove();
delete this.$el; // Delete the jQuery wrapped object variable
delete this.el; // Delete the variable reference to this node
}
});
var Item = Backbone.View.extend({
tagName: 'li',
template: _.template("<%=title %> <button name='removeItem'>Remove</button> <button name='editItem'>Edit</button>"),
events: {
'click [name=removeItem]':'removeItem',
'click [name=editItem]':'editItem'
},
initialize: function () {
this.listenTo(this.model,'change',this.render);
this.render();
},
render: function() {
this.$el.html( this.template( this.model.toJSON() ) );
this.stickit();
return this;
},
removeItem: function () {
// this.undelegateEvents();
this.unstickit();
this.remove();
delete this.$el; // Delete the jQuery wrapped object variable
delete this.el; // Delete the variable reference to this node
},
editItem: function() {
$('#main').append( new ItemForm({model: this.model }).render().el );
}
});
var Menu = Backbone.View.extend({
el: '#Menu',
template: "<button name='add'>ADD NEW</button>",
events: {
'click [name=add]': '_add'
},
initialize: function() {
this.render();
},
render: function(){
this.$el.html( this.template );
return this;
},
_add: function(){
var item = new Item({
model: new Data()
});
$('#Items').append( item.el );
}
});