Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disabling hashchange listener when updating hash programatically (jQuery BBQ)

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;
    }, 
like image 448
dani Avatar asked Nov 14 '22 21:11

dani


1 Answers

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);
like image 82
istvan.halmen Avatar answered Dec 15 '22 07:12

istvan.halmen