Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to ensure binding to hashChange event does not bubble?

I'm trying to keep my hashChange event binding from bubbling.

I have this:

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

My script manages panels on a page with each panel having it's own history-stack. The above fires with every transition, but I'm blocking the hashChange on forward transitions, so I can navigate deeper into the panel. On backwards "transitions", only hashChange fires and is not blocked, so I can go back up.

A 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... 

All works well (= hashChange fires once), until I reach the page before initial setup. On the final step the above hashChange-binding fires twice. I have tried forever to set a flag somewhere to block the 2nd hashChange, but it doesn't work as I had hoped.

Question:
How can ensure this does not bubble? I'm trying something like this, but it's not working:

var $blockBubblingHashes = 0;
$(window).bind('hashchange', function( e ) {       
   if ($blockBubblingHashes == 0) {
      // run hashChange routine
      $blockBubblingHashes = 1; 
      } else {
         $blockBubblingHashes = 0;
         }
    });
like image 919
frequent Avatar asked Oct 23 '22 17:10

frequent


1 Answers

If you want the event handler to fire only once, you should consider using the one() function, which removes the handler after it's first execution.

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

If you specifically want to stop the event bubbling, rather than removing the handler, you should checkout the stopPropagation() and stopImmediatePropagation() on methods the event object. Unfortunately, I get the impression you're binding all your hashchange handlers to the window, and jQuery does not document in which order event handlers bound to the same element are executed; so you'll have no reliable way of knowing which handler is invoked first.

like image 52
Matt Avatar answered Oct 27 '22 10:10

Matt