Вопрос

I'm trying to figure out History.js, the following code works if you go to index.html but if you try to access index.html?info directly, it displays the index content. How exactly are you supposed to detect state when somebody tries to directly access index.html?info? Also, I'm not sure if I'm doing the initial state properly either.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <title>title</title>
    <script src="js/jquery-1.10.2.min.js"></script>
    <script src="js/jquery.history.js"></script>
</head>
<body>

    <div id="content"></div>

    <script>
        History.Adapter.bind(window, 'statechange', function() {
            var id = History.getState().data.id;

            if (id == "index") {
                $('#content').html('<button id="btn" type="button">get info</button>');
                $('#btn').click(function() {
                   History.pushState({ id: "info" }, '', '?info'); 
                });
            }

            if (id == "info") {
                $('#content').html('here is some info');
            }
        });

        History.pushState({ id: "index" }, '', '?index'); //do this otherwise nothing loads on first run
    </script>

</body>
</html>
Это было полезно?

Решение

Well you are always pushing the index state in your example. What you could do is something like this: Instead of History.pushState write:

var p = window.location.search.replace( "?", "" ); //this gets you the parameter
History.replaceState({id: p}, '', '?'+p);

However, History state is preserved on refresh and as such on refreshing the page the statechange event will not fire, since the state doesn't change.

So to go around this you would need something like this:

var historyFired = false;

function onHistory() {
  //put code previously in your statechange hanlder here
  historyFired = true;
}

History.Adapter.bind(window,'statechange',onHistory);

var p = window.location.search.replace( "?", "" ); //this gets you the parameter
History.replaceState({id: p}, '', '?'+p);

if (!historyFired) onHistory();

It's a bit of a hack, but it does what you want it to do;

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top