Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

backbone.js

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 ?

like image 914
Running Turtle Avatar asked Apr 11 '13 07:04

Running Turtle


1 Answers

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

like image 164
Jake Blues Avatar answered Oct 20 '22 16:10

Jake Blues