简体   繁体   English

以编程方式更新 hash 时禁用 hashchange 监听器(jQuery BBQ)

[英]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.为了防止在设置 URL hash (#) 时出现反馈循环(与手动更改 URL 不同),我想暂时禁用 hashChange 监听器。

How should I change this code to actually disable the hashchange event when updating the hash using $.bbq.pushState(hash) ?使用$.bbq.pushState(hash)更新 hash 时,我应该如何更改此代码以实际禁用 hashchange 事件? (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.当事件处理程序中的代码执行时,hashchange 事件异步触发,hashChangeEnabled 已重置为 true。 You should reset your hashChangeEnabled in the hashchange event:您应该在 hashchange 事件中重置 hashChangeEnabled:

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:在您的 updateURL function 中,您可以检查 hash 是否已更改:

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)或使用 setTimeout 重置 hashChangeEnabled(等待 hashchange 事件触发,如果 hash 发生变化)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM