Disabling hashchange listener when updating hash programatically (jQuery BBQ)

怎甘沉沦 提交于 2019-12-23 15:35:26

问题


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;
    }, 

回答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);


来源:https://stackoverflow.com/questions/6290950/disabling-hashchange-listener-when-updating-hash-programatically-jquery-bbq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!