Restoring content when clicking back button with History.js

前端 未结 1 1479
萌比男神i
萌比男神i 2021-02-02 00:03

I\'ve implemented History.js on a local test application. Everything seems to work, however if I press the back button in the browser, the previous content does not get restored

1条回答
  •  清歌不尽
    2021-02-02 00:44

    Ok I got it, also thanks to Tobias Cohen for the hint.

    One has to store the loaded data in the history object (State.data). First let's see how the statechange callback changed:

    History.Adapter.bind(window, 'statechange', function()
    {
    
        var State = History.getState();
    
        $.each(State.data.clips, function(key, val)
        {
            $(key).replaceWith(val);
        });
    
        History.log(State.data, State.title, State.url);
    
    });
    

    As you can see, on each statechange I can access State.data.clips and replace the html content.

    NOTE: A statechange does also happen when calling History.pushState(). That means in my initial question the second code snippet is wrong in the fact that I do the content manipulation in there. There's no need for it. Just call History.pushState() and do any content manipulation within the statechange callback.

    So for completeness, this is how I push the clips into the history object:

    History.pushState({state:1, clips:data.clips}, data.title || document.title, 'http://127.0.0.1/site/www/');
    

    0 讨论(0)
提交回复
热议问题