Ajax with history.pushState and popstate - what do I do when popstate state property is null?

前端 未结 6 935
遥遥无期
遥遥无期 2021-02-07 01:18

I\'m trying out the HTML5 history API with ajax loading of content.

I\'ve got a bunch of test pages connected by relative links. I have this JS, which handles clicks on

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-07 02:05

    I realize this is an old question, but when trying to manage state easily like this, it might be better to take the following approach:

    $(window).on('popstate',function(e){
        var state = e.originalEvent.state;
        if(state != null){
            if(state.hasOwnProperty('window')){
                //callback on window
                window[state.window].call(window,state);
            }
        }
    });
    

    in this way, you can specify an optional callback function on the state object when adding to history, then when popstate is trigger, this function would be called with the state object as a parameter.

    function pushState(title,url,callback)
    {
        var state = {
            Url : url,
            Title : title,
        };
        if(window[callback] && typeof window[callback] === 'function')
        {
            state.callback = callback;
        }
        history.pushState(state,state.Title,state.Url);
    }
    

    You could easily extend this to suit your needs.

提交回复
热议问题