Skip to content

Instantly share code, notes, and snippets.

@eskimoblood
Created February 20, 2013 13:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eskimoblood/4995526 to your computer and use it in GitHub Desktop.
Save eskimoblood/4995526 to your computer and use it in GitHub Desktop.
Router that will just show a new view in a region. The router can be configurate by a simple map like this `{'someRoute/:id' : SomeView}`. So when ever a configured route matchs, the corresponding view will be shown in the passed region.
define(function() {
function getRouterSetting(region, routerSettings) {
var settings = {
appRoutes: {},
controller: {}
};
// this function is called when a routes changed
function routeFunction(View, routes) {
//first arg is always the View taht should show in the main view
//args are all additional arguments aka. the route params
var args;
if (arguments.length > 1) {
args = Array.prototype.slice.call(arguments, 2);
}
//map the route params to the name in route so /someroute/:somevalue will become {somevalue: passedArgs}
//this object will be passed under the parameter key of the options
var params = {};
var regEx = /(?::)(\w+)/g;
var match = regEx.exec(routes);
var count = 0;
while (match) {
params[match[1]] = args[count++];
match = regEx.exec(routes);
}
//create a new View and pass the additional args as options
//and show the view in the region
region.show(new View({params: params}));
}
//map the {route: View} map into
// {appRoutes: {route: uniqueName}, controller: {uniqueName: routeFunction as a closure with the View passing in}}
_.each(routerSettings, function(View, route) {
var functionName = _.uniqueId('fn_');
settings.appRoutes[route] = functionName;
settings.controller[functionName] = _.partial(routeFunction, View, route);
});
return settings;
}
return function(region, routerSettings) {
var settings = getRouterSetting(region, routerSettings);
var Router = Backbone.Marionette.AppRouter.extend(settings);
return new Router();
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment