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