Created
November 9, 2012 15:39
An ActionDispatcher Sample used for communication across angularJS scopes.
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
/** | |
* An object of ActionDispatcher is responsible for dispatching action to there registered handlers | |
* so that an action can be handled by its Action Handler. | |
* @constructor | |
*/ | |
function ActionDispatcher() { | |
var actionHandlersMap = {}; | |
/** | |
* Dispatches Action to its registered action handler. | |
* @param action the action to be handled | |
* @throw Error exception if no Action Handler is registered for this action. | |
*/ | |
this.dispatch = function (action) { | |
var actionHandlers = actionHandlersMap[action.constructor]; | |
if (actionHandlers == undefined) { | |
throw new Error('no handler for action:' + action.constructor); | |
} else { | |
for (var i = 0; i < actionHandlers.length; i++) { | |
var handler = actionHandlers[i]; | |
handler.handle(action); | |
} | |
} | |
}; | |
/** | |
* Subscribes Action to be handled by provided ActionHandler | |
* @param actionConstructor action constructor for action; | |
* @param actionHandler the action handler that will handle the action. | |
*/ | |
this.subscribe = function (actionConstructor, actionHandler) { | |
if (actionHandler.handle != undefined && (typeof actionHandler.handle == 'function')) { | |
var actionHandlers = actionHandlersMap[actionConstructor]; | |
//define if not defined | |
if (actionHandlers == undefined) { | |
actionHandlersMap[actionConstructor] = new Array(); | |
} | |
actionHandlers = actionHandlersMap[actionConstructor]; | |
actionHandlers.push(actionHandler); | |
actionHandlers[actionHandlers.length] = actionHandler; | |
} else { | |
throw new Error("adding handler with no handle method !"); | |
} | |
} | |
} | |
// Simple Action | |
function ActivitySuccessNotificationAction(message) { | |
this.getMessage = function () { | |
return message; | |
}; | |
} | |
// Simple Controller that uses ActionDispatcher to register its ActionHandlers. | |
function SimpleController($scope, $window, ActionDispatcher) { | |
function NotificationsActionHandler($scope) { | |
this.handle = function (errorNotificationAction) { | |
$scope.message = errorNotificationAction.getMessage(); | |
} | |
} | |
ActionDispatcher.subscribe(ErrorNotificationAction, new NotificationsActionHandler($scope)); | |
ActionDispatcher.subscribe(ActivitySuccessNotificationAction, new NotificationsActionHandler($scope)); | |
} | |
//A simple usage. | |
ActionDispatcher.dispatch(new ActivitySuccessNotificationAction("EveryThing is OK ")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment