2

I am building a multi-page application and would like to leverage Backbone's Router to initialize my views on page load. I haven't been able to find a way to leverage routers without using hashes and I don't need or want to use push state.

Basically, all I want to be able to do is use the Routers URL pattern matching to match the url and initialize my views depending on which page is loaded from the server.

Perhaps I am thinking about this all wrong or maybe there is a way to do this natively in Backbone Routers that I am missing. Any suggestions are greatly appreciated.

Kevin O'Hara
  • 337
  • 3
  • 14

1 Answers1

0

From the Backbone documentation (emphasis mine):

Backbone.Router provides methods for routing client-side pages, and connecting them to actions and events.

In other words, the Backbone Router was only designed to handle client-side URLS (the part after the hash), not server-side ones (the part before the hash). There might be a way to hack the Router and Backbone.History to use full URLs instead of just the hash, but it would not be easy and I'd recommend against it.

One alternative you could consider is some sort of onDocumentReady logic that checks the URL of the page and, if it's hash doesn't match it's URL, adds a hash. This would make it so that if someone visits "/foo" your code would convert it to "/foo#foo", and the Backbone Router could be used normally.

Another option though would just be to write your own "router" of sorts, which will actually be simpler than Backbone's because it only needs to work once per page load. Here's a simple example:

var mockRouter = {
    foo: function() {
        // do stuff for page "foo"
    },
    bar: ...
}
$(function() {
    mockRouter[window.location.pathname]();
});
machineghost
  • 33,529
  • 30
  • 159
  • 234