(function() { | |
function Dispatcher() { | |
this.routes = []; | |
} | |
Dispatcher.prototype.route = function route(path, action) { | |
this.routes.push({ path: path, action: action }); | |
return this; | |
}; | |
Dispatcher.prototype.dispatch = function dispache(opts) { | |
opts = opts || {}; | |
var targetPath = opts.path || location.pathname; | |
var actions = opts.actions; | |
this.routes.forEach(function(route) { | |
var path = route.path; | |
var action = route.action; | |
var match = targetPath.match('^' + path + '$'); | |
if (!match) return; | |
if (typeof action === 'function') { | |
action(match); | |
} | |
else if (typeof actions[action] === 'function') { | |
actions[action].apply(this, match); | |
} | |
else { | |
throw new Error('action is not defined'); | |
} | |
}); | |
}; | |
window.Dispatcher = Dispatcher; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment