Created
March 4, 2012 13:00
-
-
Save corpix/1972890 to your computer and use it in GitHub Desktop.
Backbone router before,after,leave
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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, _); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
routes: { | |
'index': 'index' | |
}, | |
index: { | |
before: function(){}, | |
route: function(){}, // Main route function | |
after: function(){}, | |
leave: function(){} | |
} | |
} |
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
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