Click Binding Event Using Backbone.js & jQuery

I need to bind two events in my backbone.js -view to switch the menu. The idea is that if the button with id #toggler , menu users and any click outside the #menu element #menu hide the menu.

Unfortunately, I cannot get this to work with binding to the base event without calling outsideMenuHandler() on every click, regardless of whether I clicked on the #menu element or not.

What should I change to make this work?

This is what I did in backbone.js, which does not work properly:

 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 } 

As a link, here is what I will do using jQuery only:

 $(document).click(function(event) { if ( $(event.target).closest('#menu').get(0) == null ) { $("#menu").slideUp(); } }); 
+6
source share
2 answers

There are a few things you need to figure out.

First of all, if your insideMenuHandler returns false or calls e.stopPropogation() , then your outsideMenuHandler will not be called for clicks on #menu . For instance:

http://jsfiddle.net/ambiguous/8GjdS/

But this is not your whole problem. Your outsideMenuHandler will only be called for clicks on your view; therefore, if someone clicks on a page outside of your view, your outsideMenuHandler will not be called and your menu will not work. If you want the menu to drop when someone clicks somewhere outside of #menu , you will have to manually bind to the body and manually unbind when destroying your view. Something like that:

 var myView = Backbone.View.extend({ events: { 'click #menu': 'insideMenuHandler' }, initialize: function() { _.bindAll(this, 'insideMenuHandler', 'outsideMenuHandler'); }, render: function() { // Both <body> and <html> for paranoia. $('body, html').on('click', this.outsideMenuHandler); // ... return this; }, remove: function() { // Clean up after ourselves. $('body, html').off('click', this.outsideMenuHandler); // ... }, // ... outsideMenuHandler: function(e) { // ... return false; } }); 

and then be sure to delete your view. For instance:

http://jsfiddle.net/ambiguous/MgkWG/1/

+14
source

The problem is that you are binding your event to the DOM element that you define as view el. So if it is not window.document , as in your jquery example, you will not notice that someone will click outside of them. The easiest way in your example is to add events manually using jquery, rather than using the trunk.

-1
source

Source: https://habr.com/ru/post/907257/


All Articles