I have a menu that upon click, creates a backbone view and binds controls. This happens every time I click on the menu. What I need to know is to how clear backbone objects from memory before the view is defined and rendered (on each menu click).
Otherwise, every time the menu is clicked, backbone creates a new view and rebinds all the controls. So I get something like this:
r {cid: "view1", options: Object, $el: b.fn.b.init[1], el: div#templatePlaceholder, constructor: function…}
r {cid: "view2", options: Object, $el: b.fn.b.init[1], el: div#templatePlaceholder, constructor: function…}
r {cid: "view3", options: Object, $el: b.fn.b.init[1], el: div#templatePlaceholder, constructor: function…}
note: the DOM only shows one render
EDIT: Code:
var app = {
Collection: Backbone.Collection.extend({}),
Model: Backbone.Model.extend({}),
View: Backbone.View.extend({
initialize: function(){
this.setElement($('#templatePlaceholder'));
},
render: function () {
var that = this;
Q.when(formDataGet.execute()).then(function (data) {
that.$el.html(data);
});
},
events: {
"click button[id=lbtn]": "goLeft",
"click button[id=rbtn]": "goRight"
},
goLeft: function () {
// Button clicked
console.log(this);
},
goRight: function () {
// Button clicked
console.log(this);
}
}),
};
var view = new app.View({
});
view.render();
This code gets fired every time a menu item is clicked. And this creates a new view.
I can think of two ways in core backbone (there are probably more, but it's a start)
Hold a reference to the view, when you need to close the menu, call remove()
on the view
You don't have to remove the view, you can simply show / hide it, nothing wrong with it
Use Marrionette / Chappline / LayoutManager that have some strucured ways to maintain your views
More information about your app / structure and what are the use cases will allow me to help more