To prevent a feedback loop when setting the URL hash (#) programmatically (in contrast to manually changing the URL) I want to disable the hashChange listener temporarily.
How should I change this code to actually disable the hashchange event when updating the hash using $.bbq.pushState(hash)? (code below doesn't work)
hashChangeEnabled : true,
bindHashChange : function(){
var that = this;
$(window).bind( 'hashchange', function( event ) {
if(that.hashChangeEnabled == true){
stateObj = event.getState()
that.stateChangedHandler(stateObj);
}
});
},
updateURL : function(hash){
this.hashChangeEnabled = false; // <--- Look here
$.bbq.pushState(hash);
this.hashChangeEnabled = true;
},
The hashchange event fires asyncrounously, hashChangeEnabled is already reset to true, when the code in the event handler executes. You should reset your hashChangeEnabled in the hashchange event:
if(that.hashChangeEnabled == true){
stateObj = event.getState()
that.stateChangedHandler(stateObj);
}
else {
that.hashChangeEnabled = true;
}
In your updateURL function you can check if the hash is changed:
if (hash !== $.param.fragment()) {
this.hashChangeEnabled = false;
$.bbq.pushState(hash);
}
Or reset the hashChangeEnabled with setTimeout (wait for the hashchange event to fire, if hash changed)
this.hashChangeEnabled = false;
$.bbq.pushState(hash);
setTimeout(function() { this.hashChangeEnabled = true; }, 500);
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