This is a simplified example of the projects I've worked on.
Everything is working properly but for some reason the memory usage increases, Some of the elements are not deleted from the DOM.
I have read many articles about Backbone memory leaks but it didn't help.
I'm using Backbone.stickit to model binding and I think this is causing the problem.
How should I fix this code for best memory performance? Check my sample code on jsbin and performance test video on 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 );
}
});