I need to bind two events in my backbone.js-view in order to toggle a menu. The idea is that if a button with the id #toggler is clicked the menu appears and any click outside the #menu element will hide the menu.
Unfortunately I cannot get this working with backbone’s event binding without having the outsideMenuHandler() called on every click regardless if I clicked on the #menu element, or not.
What should I change to make this work?
This is what I have done in backbone.js, which doesn’t work as intended:
myView = Backbone.View.extend({
events: {
'click #menu': 'insideMenuHandler',
'click': 'outsideMenuHandler'
}
insideMenuHandler: function(e) {}, // Called when clicking #menu
outsideMenuHandler: function(e) {} // Called on every click both on and off #menu
}
Just as a reference, here’s what I would do using jQuery alone:
$(document).click(function(event) {
if ( $(event.target).closest('#menu').get(0) == null ) {
$("#menu").slideUp();
}
});
There are a couple things you need to sort out.
First of all, if your
insideMenuHandlerreturnsfalseor callse.stopPropogation()then youroutsideMenuHandlerwon’t get called for clicks on#menu. For example:But that’s not your whole problem. Your
outsideMenuHandlerwill only be called for clicks on your view; so, if someone clicks on the page outside your view, youroutsideMenuHandlerwon’t get called and your menu won’t go down. If you want the menu to go down when someone clicks anywhere outside#menu, then you’ll have to manually bind tobodyand manually unbind when your view is destroyed. Something like this:and then be sure to properly remove your view. For example: