【问题标题】:How to change state without triggering statechange in history.js?如何在不触发 history.js 中的 statechange 的情况下更改状态?
【发布时间】:2012-07-13 09:15:41
【问题描述】:

我正在使用history.js,并且我有一个事件处理程序

$(window).bind('statechange', function(){
    // Loads the content representing the state via ajax
});

大多数内容更改是由History.pushState([...]) 在用户单击链接或按钮时触发的。

但在某些情况下,内容更改由 javascript 直接管理(即通过更改、添加或删除 DOM 元素),无需通过 ajax 加载表示新状态的内容。

不过,如果用户点击重新加载或稍后想要使用后退按钮等,我需要推送一个状态并更改 url 以反映新状态。

所以我的问题是:如何在某些情况下推送状态但避免加载内容?是否有一种标志可以传递给 statechange 事件处理程序,或者我可以完全绕过它?

【问题讨论】:

    标签: jquery ajax history.js


    【解决方案1】:

    我也想知道这个问题。我的决定是使用全局变量。例如,您可以将 window.stateChangeIsLocal 初始化为 false:

    window.stateChangeIsLocal = false;
    

    您的 statechange 处理程序可能看起来像这样:

    History.Adapter.bind(window,'statechange',function(){
        if (!window.stateChangeIsLocal) {
            someAjaxLoadFunction(History.getState().url);
        }
        else {
            window.stateChangeIsLocal = false;
        }
    });
    

    当你改变状态并且不想加载新状态的内容时,只需将window.stateChangeIsLocal设置为true;

    也许有一些更优雅的解决方案,但我找不到它们并使用它。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-29
    相关资源
    最近更新 更多