Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 688
Eli Avatar asked Mar 06 '12 10:03

Eli


3 Answers

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"

like image 164
PsyBurn Avatar answered Oct 21 '22 16:10

PsyBurn


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

like image 29
OlliM Avatar answered Oct 21 '22 15:10

OlliM


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...

like image 1
nightsurgex2 Avatar answered Oct 21 '22 17:10

nightsurgex2