Skip to content

Instantly share code, notes, and snippets.

@fritz-gerneth
Created April 10, 2013 17:22
Show Gist options
  • Save fritz-gerneth/5356617 to your computer and use it in GitHub Desktop.
Save fritz-gerneth/5356617 to your computer and use it in GitHub Desktop.
(function (Controller, Deps, _) {
"use strict";
Controller.Dispatcher = function (matchingSource, controllers) {
var self = this;
var availableControllers = controllers || [],
controllerDependants = new Deps.Dependency(),
currentController;
self.addController = function (controller) {
availableControllers.push(controller);
controllerDependants.changed();
};
Deps.autorun(function () {
var match = matchingSource(),
oldController = currentController;
controllerDependants.depend();
currentController = _.find(availableControllers, function (controller) {
return controller.canDispatch(match);
});
if (undefined !== currentController) {
currentController.dispatch(match);
}
if (oldController !== currentController && oldController !== undefined) {
oldController.destroy();
}
});
};
} (Controller, Deps, _));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment