Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating the hash programmatically without triggering hashchange event?

I'm using the jQuery BBQ plugin to push states to the location.hash.

To prevent a feedback loop, I'd like to disable the hashchange listener temporarily while setting the state programmatically.

I've seen this solution: Change hash without triggering a hashchange event

Unfortunately, it doesn't seem to be perfectly robust as it sometimes triggers even though I do this:

updateURL(obj){
  $(window).unbind( 'hashchange');
  $.bbq.pushState(obj);
  setTimeout( function() { bindHashChange()}, 500);
}

Is there now a better approach to push states programmatically? Perhaps another JS library?

like image 664
dani Avatar asked Aug 14 '11 16:08

dani


1 Answers

Doing this with a timeout will not work reliably. The important part of the linked answer is setting a flag that your handler knows about. See the updated question for code.

Alternatively, bind a temporary handler to the event that is in charge of reestablishing your handler:

function updateState(state, handler) {
    var win = $(window);

    function temporaryHandler() {
        win.unbind('hashchange', temporaryHandler);
        win.bind('hashchange', handler);
    };

    win.unbind('hashchange', handler);
    win.bind('hashchange', temporaryHandler);

    $.bbq.pushState(state);
}
like image 119
lawnsea Avatar answered Sep 22 '22 09:09

lawnsea