12

Say I have a backbone router like:

routes:
  ""                          : "homepage"
  "catalog/:id"               : "catalogPage"
  "catalog/:id/products/:id2" : "productPage"

homepage   :           -> doStuff()
catalogPage: (id)      -> doOtherStuff()
productPage: (id, id2) -> doEvenMoreStuff()

and a function:

executeBefore = -> console.log("hello")

If I want executeBefore to be called and executed each time a route is called and before the corresponding route method, is there a simple way to do it apart from inserting a call to executeBefore at the beginning of every route method ?

4 Answers 4

29

You can override the route function in your router class to intercept the route calls :

var Router = Backbone.Router.extend({
    routes: {
        "" : "homepage",
        "catalog/:id" : "catalogPage"
    },

    route: function(route, name, callback) {
        var router = this;
        if (!callback) callback = this[name];

        var f = function() {
            console.log('route before', route);
            callback.apply(router, arguments);
            console.log('route after', route);
        };
        return Backbone.Router.prototype.route.call(this, route, name, f);
    },

    homepage: function() {
        console.log("homepage");
    },
    catalogPage: function(id) {
        console.log("catalogPage "+id);
    }
});

var r = new Router();
Backbone.history.start();

And a demo http://jsfiddle.net/nikoshr/EdLzh/

2
  • 1
    This solution works well. That said the docs refer to an 'execute' method that should provide similar functionality (albeit at runtime). Doesn't work for me - has anyone else had any luck with it?backbonejs.org/#Router-execute
    – som
    Mar 23, 2014 at 7:23
  • I wanted to save the current route hash before the actual route change. Used above solution but in url hash is changed and then the 'f' function called. So the route is now the new hash and no way to get the old hash. Any idea what might i be doing wrong ?
    – ajayv
    Dec 17, 2018 at 7:42
5

Since Feb, 13, 2014, you can use router.execute(callback, args, name) (http://backbonejs.org/#Router-execute) for this.

So your interceptor will be looked something like this

routes: {
    '': 'homepage',
    'catalog/:id': 'catalogPage',
    'catalog/:id/products/:id2': 'productPage'
},
execute: function(callback, args, name) {
    // Do your stuff here
    executeBefore();

    if (callback) callback.apply(this, args);
}

https://github.com/jashkenas/backbone/commit/791033dc1aab53e9e5c9366f64a854224f851231

2

you can also use backbone.routefilter plugin.

you'll be able to set a filter for all routes

var Router = Backbone.Router.extend({
  routes: {
    "": "index",
    "page/:id": "page"
  },
  before: function( route, params ) { ... },
  after: function( route, params ) { ... },
  index: function(){ ... },
  page: function( route ){ ... }
});

Or select some routes

var Router = Backbone.Router.extend({
  routes: {
    "": "index",
    "page/:id": "page"
  },
  before: {
    "": function( route ) { ... },
    "page/:id": function( route ) { ... }
  },
  after: function( route ) { ... },
  index: function(){ ... },
  page: function( route ){ ... }
});
-1

You can play with the Events :

Backbone.history.on('route', function () {
    // Do your stuff here.
    executeBefore();
});

visiting #help/uploading will fire a route:help event from the router.

Apparently, this would be triggered before the redirection :

https://github.com/documentcloud/backbone/blob/master/backbone.js#L1243

Backbone.history.route(route, function(fragment) {
    var args = router._extractParameters(route, fragment);
    callback && callback.apply(router, args);
    router.trigger.apply(router, ['route:' + name].concat(args));
    router.trigger('route', name, args);
    Backbone.history.trigger('route', router, name, args);
});
1
  • I think your answer is wrong because if one uses Backbone router by calling router.navigate(route, options); will first execute the route callback and the event 'route' callback. I tested this myself. Sorry for not providing a fiddle.
    – bboydflo
    Jul 15, 2015 at 12:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.