Skip to content

Instantly share code, notes, and snippets.

@Willmo36
Created January 20, 2015 17:25
Show Gist options
  • Save Willmo36/8d4538f7b2e00fa189d2 to your computer and use it in GitHub Desktop.
Save Willmo36/8d4538f7b2e00fa189d2 to your computer and use it in GitHub Desktop.
Run actions on active routes
//This could be massively improved and documented
function RunRouteActions(dispatcher, routes, state){
var actionsToRun = [];
var actionIndex = 0;
var activeRouteNames = state.routes.map(function (route) {
return route.name;
});
function traverseRoute(route) {
var props = route._store.props;
if (props.actions) {
//an action must be a function
//props.actions can be an array of actions or single action
//case to add lodash
props.actions.constructor == Array
? props.actions.forEach(addAction)
: addAction(props.actions);
}
//If we have kids, run the same process on them
if (props.children) {
props.children.constructor == Array
? props.children.forEach(traverseChild)
: traverseChild(props.children);
}
function addAction(action) {
//case to add lodash
if (typeof(action) != 'function')
throw Error('Route actions must be a function or an array. ' + route.name);
actionsToRun.push(action);
}
function traverseChild(child) {
if (isActiveRoute(child)) traverseRoute(child);
}
function isActiveRoute(route) {
if (!route._store.props && !route._store.props.name) return false;
return activeRouteNames.indexOf(route._store.props.name);
}
}
function runAction(index){
if(!actionsToRun[index]) return;
actionsToRun[index](dispatcher, state.params,function(){
actionIndex++;
runAction(actionIndex);
})
}
traverseRoute(routes);
if(actionsToRun.length > 0)
runAction(0);
}
module.exports = RunRouteActions;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment