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?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With