8

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?

Community
  • 1
  • 1
dani
  • 4,880
  • 8
  • 55
  • 95

1 Answers1

2

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);
}
lawnsea
  • 6,463
  • 1
  • 24
  • 19