Created
December 5, 2014 19:54
-
-
Save ianmetcalf/88efece93e652c930bae to your computer and use it in GitHub Desktop.
Chainable Async Router
This file contains 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
var ChainableRouter = BaseRouter.extend({ | |
constructor: function(options) { | |
BaseRouter.apply(this, arguments); | |
this.options = options || {}; | |
this._initRoutes(); | |
}, | |
_initRoutes: function() { | |
var routes = this.getOption('appRoutes'), | |
controller = this.getOption('controller'); | |
if (!routes) { return; } | |
// Backbone requires reversed order of routes | |
_.chain(routes).keys().reverse().each(function(key) { | |
this.addRoute(key, routes[key], controller); | |
}, this); | |
}, | |
addRoute: function(route, handlers, controller) { | |
this.route(route, _.map(_.isArray(handlers) ? handlers : [handlers], function(handler) { | |
var method; | |
if (_.isFunction(handler)) { return handler; } | |
if (!controller) { | |
throw new Error('A controller must be specified for route "' + route + '"'); | |
} | |
method = controller[handler]; | |
if (!method) { | |
throw new Error('Method "' + handler + '" was not found on the controller'); | |
} | |
return _.bind(method, controller); | |
})); | |
}, | |
onNavigate: function(routeData) { | |
var index = 0, | |
that = this; | |
this._currentRoute = routeData; | |
function next(resp) { | |
var handler = routeData.linked[index]; | |
index += 1; | |
if (handler && that._currentRoute === routeData) { | |
handler(resp || routeData, next); | |
} | |
} | |
next(); | |
}, | |
// Proxy `getOption` to enable getting options from this or this.options by name. | |
getOption: Marionette.proxyGetOption | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment