Implementation of History.js

后端 未结 2 1633
死守一世寂寞
死守一世寂寞 2021-01-31 05:48

I am trying to implement History.js for my ajax site so that I can use forward and back buttons and even bookmarks. However the example @ https://github.com/browserstate/History

相关标签:
2条回答
  • 2021-01-31 06:19

    Refer this question: Implementing "Back button" on jquery ajax calls

    Some more info related to RSH

    How to implement RSH (Really Simple History) for Ajax History Back Button

    0 讨论(0)
  • 2021-01-31 06:23

    I had trouble fully understanding how to use History.js. Here is some code from their wiki with my comments for explanation:

    1. Get a reference to the history.js object

    To get a reference to the History.js object reference window.History (Capitol 'H').

    var History = window.History;
    

    To check if HTML5 history is enabled check History.enabled. History.js will still work using hash tags if it is not.

    History.enabled
    

    2. Listen for history changes and update your view from here

    To listen for history state changes bind to the statechange event of the Adapter object.

    History.Adapter.bind(window,'statechange',function(){ 
        var State = History.getState(); 
        History.log(State.data, State.title, State.url);
    });
    

    3. Manipulate history states by using push or replace

    To add a state to the history, call pushState. This will add a state to the end of the history stack which will trigger the 'statechange' event as shown above.

    History.pushState({data:"any kind of data object"}, "State Title", "?urlforthestate=1"); 
    

    To replace a state to the history, call replaceState. This will replace the last state in the history stack which will trigger the 'statechange' event as shown above.

    History.replaceState({data:"any kind of data object"}, "State Title", "?urlforthestate=1"); 
    

    The difference between pushState and replaceState is that pushState will add a state to the history list, replaceState will overwrite the last state.

    NOTE: pushState and replaceState serialize the data object, so use minimal data there.

    4. If you want to add additional ui for the user to be able to navigate the history, use the navigation commands

    Use back and go to navigate the history via code.

    History.back();
    History.go(2);
    

    Additional: Using "a" tags with history

    To use "a" tags with history you will need to intercept click events and prevent the browser from navigating by using the event.preventDefault() method.

    Example:

    <a href="dogs/cats" title="Dogs and cats">Dogs and Cats</a>
    
    $('a')​.click(function(e){
        e.preventDefault();
        var url = $(this).attr('href');
        var title = $(this).attr('title');
        History.pushState({data:title}, title, url);
    })​;
    

    I hope this helps.

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