Navigatron
Navigatron

Reputation: 2115

History.js and states

Would someone please explain states to me?

For instance, with the history.js plugin.

History.pushState({state:1}, "State 1", "?state=1"); // logs {state:1}, "State 1", "?state=1"

I understand the last parameter, as it's the URL that's pushed to the address bar, but I have no idea of the first two. Understanding these would help me implement history.js into my site, as I'm having trouble with back/forward navigation.

On the Mozilla dev site it says:

state object — The state object is a JavaScript object which is associated with the new history entry created by pushState(). Whenever the user navigates to the new state, a popstate event is fired, and the state property of the event contains a copy of the history entry's state object. The state object can be anything that can be serialized. Because Firefox saves state objects to the user's disk so they can be restored after the user restarts her browser, we impose a size limit of 640k characters on the serialized representation of a state object. If you pass a state object whose serialized representation is larger than this to pushState(), the method will throw an exception. If you need more space than this, you're encouraged to use sessionStorage and/or localStorage.

Is state just a copy of the code that was loaded using AJAX? Or is it just a representation of that code, so it can be called upon?

Any insight to this is appreciated!

Upvotes: 3

Views: 1202

Answers (1)

chrisfrancis27
chrisfrancis27

Reputation: 4536

The state object is any Javascript object - it can be a single variable, or a huge hashmap of functions and values. It's whatever data you want to use to represent the 'state' of your app at that point in time. Something like this is quite common:

var viewModel = {
    title: 'FAQs',
    url: 'faqs.html',
    favouriteColor: 'green',
    stepsCompleted: 4
};

history.pushState(viewModel, viewModel.title, viewModel.url);

That's basically creating an object with anything needed to 'remember' and restore the state later - for instance if the user is following a wizard-style step-by-step form or suchlike.

The second parameter, title, is largely ignored by browsers for the time being, but is probably intended for use-cases like forwards/backwards navigation, where the page title might need to be updated.

Upvotes: 6

Related Questions