How to change state without triggering statechange in history.js?
Asked Answered
M

1

8

I am using history.js and I have an event handler

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

Most content changes are triggered by History.pushState([...]) when the user clicks a link or a button.

But in some cases the content change is managed by javascript directly (i.e. by changing, adding or removing a DOM element) and there is no need to load the content representing the new state via ajax.

Still, I need to push a state and change the url to reflect the new state, should the user hit reload or later want to use the back button etc.

So my question is: How do I push a state but avoid loading the content in some cases? Is there a kind of flag that can be passed to the statechange event handler or can I circumvent it altogether?

Multifoil answered 13/7, 2012 at 9:15 Comment(0)
D
7

I wondered about this question too. My decision was to use a global variable. For instance, you can initialize window.stateChangeIsLocal as false:

window.stateChangeIsLocal = false;

Your statechange handler could be looking something like this:

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

When you change the state and do not want to load a content of a new state, just set window.stateChangeIsLocal as true;

Maybe there are some more elegant solutions, but I couldn't find them and use this.

Derail answered 16/10, 2012 at 15:37 Comment(1)
My own solution was something similar, except I set a property of the global History object. See also this question (#8744987) for more on the issue.Multifoil

© 2022 - 2024 — McMap. All rights reserved.