public
Created

An ActionDispatcher Sample used for communication across angularJS scopes.

  • Download Gist
ActionDispatcher.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
/**
* 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 "));

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.