Backbone JS Routing not working as I expect

12,149

Solution 1

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"

Solution 2

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

Solution 3

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

Share:
12,149
Eli
Author by

Eli

Updated on July 30, 2022

Comments

  • Eli
    Eli over 1 year

    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?

  • Kinergy
    Kinergy over 9 years
    {trigger: true} isn't part of the solution here. Backbone will default to trigger:true if no options are specified. Here's the code snippet: navigate: function(fragment, options) { if (!History.started) return false; if (!options || options === true) options = {trigger: !!options};
  • NuclearPeon
    NuclearPeon about 8 years
    Your link has 404'd.