createbang
createbang

Reputation: 2423

Backbone router.route isn't setting route

I have the following router defined, but the .route function doesn't seem to be setting. What am I doing wrong? Thanks, in advance, for the help.

# app.js.coffee

initialize: =>
  router = new Backbone.Router
  router.route "foo/:bar", "baz"
  console.log router.routes # returns undefined

Upvotes: 0

Views: 1222

Answers (1)

McGarnagle
McGarnagle

Reputation: 102733

The routes you create using Router.route are stored internally in the History object -- they're not added to the Router.routes collection.

They still work though, see here for proof. Note that in this.routes, only the home route is defined, but you're still able to hit the baz route. You can see the baz route if you check Backbone.history.handlers, which is where the routes are actually stored.

var Router = Backbone.Router.extend({
    initialize: function() {
        this.route("foo/:bar", "baz");
    },
    routes: {
        "": "home"  
    },
    home: function() {
        console.log("home hit");
    },
    baz: function(bar) {
        console.log('test hit: ' + bar);
    },
});
var router = new Router();
console.log(this.routes);
console.log(Backbone.history.handlers);
Backbone.history.start();
router.navigate("foo/testbar", { trigger: true });   


Note though, I think you need to use this in your code, because router won't be defined yet inside initialize:

@route "foo/:bar", "baz"

Upvotes: 3

Related Questions