Eli
Eli

Reputation: 2696

Backbone JS Routing not working as I expect

I think I'm missing some basics about Backbone's routing functions.

I'm building an app and it looks something like so:

file: app.js

App = {}
App.nav = new Backbone.Router;
require('app/controller');

file: controller.js

App.nav.route('home', 'home', function () {
    console.log("Home Activated");
});

App.navigate('home');

At this point the browser changes the URL in the address bar to /home but nothing happens and I don't get the Home Activated console message.

I've tried using my own routing class (i.e. Backbone.Router.extend({})) but I don't really see a point in it as I still need to initialize it, and I want to use a central history/navigation in my app that all modules/controllers add routing to it rather than creating a router for every controller.

What am I doing wrong?

Upvotes: 6

Views: 12174

Answers (3)

nightsurgex2
nightsurgex2

Reputation: 250

I just want to point this out as it saved me a world of hurt and heartache.

If you are routing to a custom page such as

Backbone.router.navigate('/some/page'); // does not work

And it appears to not be working. Add a trailing '/'

Backbone.router.navigate('/some/page/'); // works

This cost me a few hours of troubleshooting...

Upvotes: 1

PsyBurn
PsyBurn

Reputation: 231

http://documentcloud.github.com/backbone/#Router-navigate

From the documentation:

If you wish to also call the route function, set the trigger option to true.

But as OlliM wrote, you need to activate the history first!

So your answer should be:

Backbone.history.start();
App.nav.navigate('home', {trigger: true});

edit: forgot to put "nav"

Upvotes: 15

OlliM
OlliM

Reputation: 7113

For the routing to work, you need to call Backbone.history.start() after setting up your routes (basically after you've done everything else). See: http://documentcloud.github.com/backbone/#History-start

Upvotes: 6

Related Questions