Skip to content

Instantly share code, notes, and snippets.

@corpix
Created March 4, 2012 13:00
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save corpix/1972890 to your computer and use it in GitHub Desktop.
Save corpix/1972890 to your computer and use it in GitHub Desktop.
Backbone router before,after,leave
(function(Backbone, _) {
var leave;
_.extend(Backbone.Router.prototype, Backbone.Events, {
route : function(route, name, callback) {
var before
, fn = callback
, after;
Backbone.history || (Backbone.history = new Backbone.History);
if (!_.isRegExp(route)) route = this._routeToRegExp(route);
if (!fn) fn = this[name];
if(typeof callback == 'object'){
before = callback.before;
fn = callback.route;
after = callback.after;
}
Backbone.history.route(route, _.bind(function(fragment) {
var args = this._extractParameters(route, fragment);
if(leave){
if(leave.apply(this, args) === false)
return;
else
leave = false;
}
if(before && before.apply(this, args) === false) return;
fn.apply(this, args);
if(after && after.apply(this, args) === false) return;
if(typeof callback == 'object')
leave = callback.leave;
this.trigger.apply(this, ['route:' + name].concat(args));
Backbone.history.trigger('route', this, name, args);
}, this));
return this;
}
});
}).call(this, Backbone, _);
{
routes: {
'index': 'index'
},
index: {
before: function(){},
route: function(){}, // Main route function
after: function(){},
leave: function(){}
}
}
@richardassar
Copy link

Hi, thanks for this.

I noticed that callback was undefined, in the original Backbone.prototype.route function there is a line if (!callback) callback = this[name];

See my clone of this gist https://gist.github.com/richardassar/5126900

@richardassar
Copy link

I've also updated my copy to provide the correct arguments to the leave function (instead I was getting the arguments for the subsequent route).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment