dani
dani

Reputation: 5000

Routing for flexible JavaScript Single-Page-App?

I'm building a single page web app (because I want flexibility and speed when moving across pages/states) but I'm struggling with routing / urls ...

In the traditional paradigm I would have urls such as:

example.com/tools/population-tool/#currentYear=1950
example.com/tools/income-tool/#country=usa
example.com/nice-story/
example.com/nice-chapter/nice-story/

Now I'd like to replace this with a Router (for example using Backbone) that loads templates and controllers for the corresponding routes.

I'm thinking about having a pages object that stores the necessary page information:

pages : {
  tools : {
    template : "#tools",
    breadcrumb : ["Home","Tools"]
  }
  nice-story : {
    template : "#nice-story",
    breadcrumb : ["Home","Stories","Nice Story"]
  }  
}

With a router, I'd now like load the right content and page state, given a url like:

example.com/#!/tools/population-tool/?currentYear=1950

or like this if not using Hashbang:

example.com/tools/population-tool/?currentYear=1950

How would you organize this routing so that the url scheme makes sense while still being flexible and allow for redirects and new query string paramaters?

Upvotes: 2

Views: 2118

Answers (1)

maxl0rd
maxl0rd

Reputation: 1446

This is not a complete answer to your question, but a few tips on Backbone...

You may want to define a method like loadPage() on your router which can empty and replace your main page container with a view that corresponds to each "page" in your app. Each route action can call that to load up the right view.

If you will be using pseudo query strings, make sure to add a matcher for them explicitly in your Backbone routes. For example:

'/tools/population-tool/?*params'

That will call your route action with the entire params string as the first parameter. You'll need to parse that...

Upvotes: 2

Related Questions