Skip to content

Instantly share code, notes, and snippets.

@aerith
Created October 28, 2010 11:37
Show Gist options
  • Save aerith/651172 to your computer and use it in GitHub Desktop.
Save aerith/651172 to your computer and use it in GitHub Desktop.
動けばいいな、動くかな。
var dispatcher = {
dispatchees: [],
connect: function (pattern, action, options) {
dispatcher.dispatchees.push({
pattern: pattern,
action: action,
options: options || {}
});
return dispatcher;
},
match: function (pattern, data) {
if (pattern instanceof RegExp) {
return pattern.exec(data.pathname);
}
return false;
},
dispatch: function (info, options) {
var data = (typeof info == 'object' && 'pathname' in info) ? info : { pathname: info.toString() };
var length = dispatcher.dispatchees.length;
for (var i = 0; i < length; i++) {
var dispatchee = dispatcher.dispatchees[i];
var matches = dispatcher.match(dispatchee.pattern, data);
if ( matches ) {
if ( dispatchee.options.onMatchedToPath &&
typeof dispatchee.options.onMatchedToPath == 'function' ) {
to_process = dispatchee.options.onMatchedToPath.apply(dispatchee, [data, options]);
if (!to_process) continue;
}
if (dispatchee.action && typeof dispatchee.action == 'function') {
var to_chain = dispatchee.action.apply(dispatchee, [data, matches, options || {}, i]);
if (!to_chain) return {
dispatchee: dispatchee,
matches: matches,
data: data
};
continue;
}
return true;
}
}
return false;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment