Question

I've got a router defined as such:

var MyRouter = Backbone.Router.extend({
  routes: {
    // catch-all for undefined routes
    "*notfound" : "notFound",
  },

  initialize: function(options) {
    this.route("my_resource/clear_filters", 'clearFilters');
    this.route("my_resource/:id", 'show');
  },

  show: function(id){
    console.log('show', id);
  },

  clearFilters: function() {
    console.log('clearFilters');
  },

  notFound: function() {
    console.log('notFound');
  },
});

var app = {};
app.MyRouter = new MyRouter();
Backbone.history.start({silent: true});

Thus the following URLs would map as:

var opts = {trigger: true};
app.MyRouter.navigate('/foo', opts);                       // logged -> 'notFound'
app.MyRouter.navigate('/my_resource/123', opts);           // logged -> 'show', '123'
app.MyRouter.navigate('/my_resource/clear_filters', opts); // logged -> 'clearFilters'
app.MyRouter.navigate('/my_resource/some_thing', opts);    // logged -> 'show', 'some_thing'

How can I restrict the my_resource/:id route to only match on numeric parameters so that app.MyRouter.navigate('/my_resource/some_thing') is handled by notFound?

Was it helpful?

Solution

From the fine manual:

route router.route(route, name, [callback])

Manually create a route for the router, The route argument may be a routing string or regular expression. Each matching capture from the route or regular expression will be passed as an argument to the callback.

So you can always say things like:

this.route(/my_resource\/(\d+)/, 'show')

in your router's initialize if you need finer grained control over the routes than Backbone's string patterns give you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top