Skip to content

Instantly share code, notes, and snippets.

@werelax
Created July 18, 2014 08:53
Show Gist options
  • Save werelax/a3dbad94ce3b069510f8 to your computer and use it in GitHub Desktop.
Save werelax/a3dbad94ce3b069510f8 to your computer and use it in GitHub Desktop.
Backbone.Router extension with before and after hooks
define(function(require, exports, module) {
"use strict";
var Backbone = require("backbone"),
_ = require("underscore");
function maybeApply(fn, ctx, args) {
if (fn) {
return fn.apply(ctx, args);
}
}
function capitalize(str) {
return str[0].toUpperCase().concat(str.slice(1));
}
module.exports = Backbone.Router.extend({
route: function(route, name, callback) {
if (_.isString(name)) {
callback = _.bind(function() {
var data = maybeApply(this.beforeAll, this, arguments);
data = maybeApply(this["before" + capitalize(name)], this, [].concat(arguments, data)) || data;
data = maybeApply(this[name], this, [].concat(arguments, data)) || data;
data = maybeApply(this["after" + capitalize(name)], this, [].concat(arguments, data)) || data;
maybeApply(this.afterAll, this, [].concat(arguments, data));
}, this);
}
return module.exports.__super__.route.call(this, route, name, callback);
}
});
});
@werelax
Copy link
Author

werelax commented Jul 18, 2014

Just be careful and avoid saving references to short-living objects (like Views!) to prevent leaks.

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