为了防止在以编程方式设置URL哈希(#)时出现反馈循环(与手动更改URL相反),我想暂时禁用hashChange侦听器。
当使用$.bbq.pushState(hash)更新哈希时,我应该如何更改此代码以实际禁用hashchange事件?(下面的代码不起作用)
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:
if(that.hashChangeEnabled == true){
stateObj = event.getState()
that.stateChangedHandler(stateObj);
}
else {
that.hashChangeEnabled = true;
}
在您的updateURL函数中,您可以检查哈希是否已更改:
if (hash !== $.param.fragment()) {
this.hashChangeEnabled = false;
$.bbq.pushState(hash);
}
或者使用setTimeout重置hashChangeEnabled(如果hash更改,请等待hashchange事件触发)
this.hashChangeEnabled = false;
$.bbq.pushState(hash);
setTimeout(function() { this.hashChangeEnabled = true; }, 500);