dthree dthree - 4 months ago 12
Javascript Question

Backbone Routes - trigger route on page load

This is a simple question, but I am new to routing and haven't been able to find an answer to this.

I have a Marionette Router (if I intimidate you, its really the same thing as a Backbone Router. Very simple).

sys.routes = {
"app/:id": "onAppRoute",

sys.Router = new Marionette.AppRouter({
controller: {
onAppRoute: function(route) {
console.log('Called app route!');
appRoutes: sys.routes,

Backbone.history.start({pushState: true})

This works - if you hit the back button my browser, the url will change within my Single Page Application and will call the

However, let's say I open a new browser window and paste in my page url to a certain 'app':


This doesn't call the
function. It doesn't even seem like it should, though, but I really don't know.

I want it to.

I don't know if I am doing it wrong, or if I should just manually fire it by grabbing my page url on page load, parsing it, then 'navigating' to that route. Seems hacky.

Answer Source

Contrary to your intuition, backbone's default behaviour is to trigger matching routes on page load! cf. http://backbonejs.org/#Router - look for the option silent: true. You'd have to specify that for the router to IGNORE your matching routes on page load, i.e. not trigger the corresponding callbacks.

So your problem lies somewhere else: your routes do NOT match the url you have stated as an example. Clearly, you require an :id parameter, trailing http://localhost/app/myApplication. Therefore, http://localhost/app/myApplication/213 would cause your callback to be triggered on page load, given you didn't pass silent: true as an option to backbone.history.start().

If you want to match the 'root' url, i.e. no params, you would define the following route:

routes: {
    '/': someFunction