Skip to content

Instantly share code, notes, and snippets.

@hokaccha
Last active December 11, 2017 05:27
Show Gist options
  • Save hokaccha/9885783 to your computer and use it in GitHub Desktop.
Save hokaccha/9885783 to your computer and use it in GitHub Desktop.
(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