Created
July 18, 2014 08:53
-
-
Save werelax/a3dbad94ce3b069510f8 to your computer and use it in GitHub Desktop.
Backbone.Router extension with before and after hooks
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
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); | |
} | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just be careful and avoid saving references to short-living objects (like Views!) to prevent leaks.