5

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;
    }, 
James Allardice
  • 164,175
  • 21
  • 332
  • 312
dani
  • 4,880
  • 8
  • 55
  • 95

1 Answers1

1

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);
istvan.halmen
  • 3,320
  • 1
  • 23
  • 29
  • Problem is that BBQ doesn't check if the new state is really different. So If I push the same state, hashChangeEnabled will be set to "false" and not reset to "true" because you do that within the hashchange listener which is never triggered ..!? Thanks! – dani Jun 09 '11 at 14:51