Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

This is a question about modern web apps, where a single page is loaded, and all subsequent navigation is done by XHR calls and modifying the DOM.

We can use libraries that manipulate the hash string, which let us navigate by URL and support the back/forward buttons.

But to use those libraries, we need to be able to move the UI from any one state to any other. Is there a good strategy for moving between UI states, that also allows them to be restored from scratch when you load a new URL?

In a complex app, you might have a lot of different states. You don't want to reload the entire UI each time you change states. But you also don't want to require separate methods for moving from every state to every every state.

Typically we need to:

  • Restore a state from scratch, when you enter a new URL or hit Reload.
  • Move from one state to another, when you use the Back/Forward buttons.
  • Move from one state to another, when you perform an action within your app (like clicking a link).
  • Move to certain states that shouldn't be added to the history, like ones that appear after form submissions.
  • Move to some states that are built on the previous state, like a drill-down list.

When you perform actions within your app, there's the additional question of which comes first:

  • Do you change the URL, listen for the URL change, and change your state in response to it?
  • Or do you change your state, then change the URL, but don't do anything in response?

Does anyone have some experience to share on this topic?

share|improve this question
1  
I would definitely love to get linked to some thorough answers to this question. I do not have a clear model in my mind for dealing with this problem. –  TehShrike Mar 25 '12 at 0:12
add comment

1 Answer

You'll want to change the url, listen for changes to the url, and change the state of the page in response to url changes. This way when the user reloads, hits the back button, or performs an action on the page, the same code will be handling the page's state changes.

The code that handles the state changes can look at the current state of the page, compare that to the new requested state of the page, and perform only the actions needed for the parts of the page that have changed.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.