Search code examples
backbone.js

How can I run a "middleware" function before a route method is executed?


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 ?


Solution

  • 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/