Why must I create a whole close prototype just to have my events unbinded from my view? Shouldn't Backbone just build that in? Is there a way to detect when a view is being removed?
My backbone events fire twice after I navigate away and back to the view.
events : {
"click #userDropdownButton > a" : "toggleUserDropdownMenu",
"click" : "hideUserDropdownMenuIfClickedOutside"
},
el : "body",
initialize : function() {
this.render();
},
// Shows/hides the user dropdown menu
toggleUserDropdownMenu : function() {
if(!this.$el.find('#userDropdownButton > ul').is(':visible')) {
this.showUserDropdownMenu();
} else {
this.hideUserDropdownMenu();
}
return false;
},
showUserDropdownMenu : function() {
this.$el.find('#userDropdownButton').addClass('hover');
this.$el.find('#userDropdownButton > ul').show();
this.$el.find('#userDropdownButton > a .arrow-down').removeClass('arrow-down').addClass('arrow-up');
},
hideUserDropdownMenuIfClickedOutside : function() {
if(this.$el.find('#userDropdownButton > ul').is(':visible')) {
this.hideUserDropdownMenu();
}
},
hideUserDropdownMenu : function() {
this.$el.find('#userDropdownButton').removeClass('hover');
this.$el.find('#userDropdownButton > ul').hide();
this.$el.find('#userDropdownButton > a .arrow-up').removeClass('arrow-up').addClass('arrow-down');
},
The first time the view is rendered, the dropdown opens and closes properly, but on the second time the view is rendered, the dropdown interprets every click twice, so as soon as it opens, the second click closes it.
undelegateEvents()
. – Stiversv.remove()
to get rid of it, that just callsthis.$el.remove()
by default and removing the element takes the delegated events with it. If you're binding a view to an existing element then you have to adjustremove
accordingly, I don't see why that's a problem. – Vashtivashtia