How to ensure binding to the hashChange event does not bubble?

I am trying to keep the hashChange event binding from bubbling.

I have it:

$(window).bind('hashchange', function( e ) { console.log("hash fired"); // run hashChange routine }); 

My script controls the panels on the page with each panel having its own history stack. The above lights with every transition, but I block hashChange on the advanced transitions, so I can move deeper into the panel. In the opposite direction, β€œtransitions” are only hash-changer lights and are not blocked, so I can return.

Navigation might look like this:

 panel A, start down > page2 panel A, page2 down > page3 panel A, page3 up > page2 panel A, page2 up > start - hashChange fires twice here... 

Everything works well (= hashChange works once) until I get to the page before the initial setup. In the last step, the above hash binding is bound twice. I tried to permanently set the flag somewhere to block the 2nd hash changer, but it does not work as I hoped.

Question:
How to ensure that it does not bubble? I am trying something like this, but it does not work:

 var $blockBubblingHashes = 0; $(window).bind('hashchange', function( e ) { if ($blockBubblingHashes == 0) { // run hashChange routine $blockBubblingHashes = 1; } else { $blockBubblingHashes = 0; } }); 
+4
source share
1 answer

If you want the event handler to be run only once, you should use the one() function, which removes the handler after the first execution.

 $(window).one('hashchange', function( e ) { console.log("hash fired");  // run hashChange routine }); 

If you specifically want to stop the bubble event, instead of removing the handler, you should check stopPropagation() and stopImmediatePropagation() about the methods of the event object. Unfortunately, I get the impression that you are binding all your hashchange handlers to a window , and jQuery does not document in what order the event handlers that are associated with the same element are executed; therefore, you will not have a reliable way to find out which handler is called first.

+2
source

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


All Articles