Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
backbone.middleware.js
/**
* @module backbone.middleware
* author eray <relfishere@gmail.com>
*/
(function (factory) {
if (typeof define === 'function' && define.amd) {
define(['backbone', 'underscore'], factory);
} else if (typeof exports === 'object') {
module.exports = factory(require('backbone'), require('underscore'));
} else {
factory(window.Backbone, window._);
}
})(function (Backbone, _) {
var noFunction = '';
var baseRoute = Backbone.Router.prototype.route;
_.extend(Backbone.Router.prototype, {
route: function(route, name, callback) {
var middleware = noFunction;
if (_.isFunction(name)) {
callback = name;
name = '';
}
if (_.isObject(name)) {
middleware = name.m;
name = name.f;
}
if (!callback) {
callback = this[name];
}
return baseRoute.call(this, route, name, _.bind(function() {
for (var functionName in this.use) {
this.use[functionName]();
}
if (_.isFunction(middleware)) {
var args = arguments;
middleware.apply(this, [
route,
_.toArray(arguments),
_.bind(function () {
if(callback) {
callback.apply(this, args);
}
}, this)
]);
} else {
if(callback) {
callback.apply(this, arguments);
}
}
}, this));
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment