Backbone.js — Call method before/after a route is fired

Levi McCallum picture Levi McCallum · Sep 13, 2011 · Viewed 7.8k times · Source

I want a setup/teardown method to be called before and after a route is fired in my Backbone.js router, respectively. Has anyone created an elegant way of doing this?

Answer

Alex Craft picture Alex Craft · Oct 8, 2011

_.wrap is not a solution, if You have for example 20 routes you have to wrap them all.

But you can do this with metaprogramming

class Backbone.FlexRouter extends Backbone.Router
  route: (route, name, handler) ->
    super route, name, ->
      @trigger "route:before"
      handler()
      @trigger "route:after"

UPD: I believe in JS it should be something like this (but I didn't tested it)

var rp = Backbone.Router.prototype
rp.routeWithoutEvents = rp.route
rp.route = function(route, name, handler){
  var that = this
  this.routeWithoutEvents(route, name, function(){
    that.trigger("route:before")
    handler()
    that.trigger("route:after")
  })
}