以编程方式更新散列时禁用hashchange侦听器(jQuery BBQ) [英] Disabling hashchange listener when updating hash programatically (jQuery BBQ)
问题描述
为了防止以编程方式设置URL哈希(#)时的反馈循环(与手动更改URL相反)我想暂时禁用hashChange侦听器。
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.
使用 $ .bbq.pushState更新哈希值时,如何更改此代码以实际禁用hashchange事件(散)? (下面的代码不起作用)
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;
},
推荐答案
hashchange事件异步触发,当事件处理程序中的代码执行时,hashChangeEnabled已经重置为true。您应该在hashchange事件中重置hashChangeEnabled:
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;
}
在updateURL函数中,您可以检查散列是否已更改:
In your updateURL function you can check if the hash is changed:
if (hash !== $.param.fragment()) {
this.hashChangeEnabled = false;
$.bbq.pushState(hash);
}
或者使用setTimeout重置hashChangeEnabled(等待hashchange事件触发,如果哈希改变了)
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);
这篇关于以编程方式更新散列时禁用hashchange侦听器(jQuery BBQ)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!