Disabling a hashchange receiver when updating a hash programmatically (jQuery BBQ)

To avoid feedback when setting the URL hash (#) programmatically (as opposed to manually changing the URL), I want to temporarily disable the hashChange listener.

How do I change this code to actually disable the hashchange event when updating the hash with $ .bbq.pushState (hash) ? (the code below does not 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;
    }, 
+3
source share
1 answer

The hashchange event is fired asyncrounously, hashChangeEnabled is already reset to true when the code in the event handler is executed. You must 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 has changed:

if (hash !== $.param.fragment()) {
  this.hashChangeEnabled = false;
  $.bbq.pushState(hash);
}

reset hashChangeEnabled with setTimeout (, hashchange , )

this.hashChangeEnabled = false;
$.bbq.pushState(hash);
setTimeout(function() { this.hashChangeEnabled = true; }, 500);
0

All Articles