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?

balupton
  • 47,113
  • 32
  • 131
  • 182
jgivoni
  • 1,605
  • 1
  • 15
  • 24

1 Answers1

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.

serg66
  • 1,148
  • 1
  • 17
  • 31
  • My own solution was something similar, except I set a property of the global History object. See also this question (http://stackoverflow.com/questions/8744487/statechange-is-firing-whenever-i-do-a-push-state?rq=1) for more on the issue. – jgivoni Oct 19 '12 at 18:52