Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
An event broker for angularjs app
(function() {
'use strict';
angular
.module('myModule')
.provider('eventBroker', eventBroker);
/* @ngInject */
function eventBroker() {
var that = this;
this.managedEvents = 'event1, event2, event3, event4';
this.$get = eventBrokerFactory;
function eventBrokerFactory($rootScope) {
var service = {};
var events = that.managedEvents.split(',');
events.forEach(function(event) {
service[event.trim()] = createEmitBroadcastAndOnForEvent('MYPREFIX' + event.toUpperCase(), $rootScope)
});
return service;
}
}
/**
* creates three function for managing eventName event on scope scope
* the newly generated functions get the same parameters of angularjs same functions,
* saving the event name
* @param eventName
* @param scope
* @returns {{emit: *, broadcast: *, on: *}}
*/
function createEmitBroadcastAndOnForEvent(eventName, scope) {
return {
emit: addEventNameToFunctionArgs(scope.$emit),
broadcast: addEventNameToFunctionArgs(scope.$broadcast),
on: addEventNameToFunctionArgs(scope.$on)
};
function addEventNameToFunctionArgs(func) {
return function() {
var args = Array.prototype.slice.call(arguments);
args.unshift(eventName);
func.apply(scope, args)
}
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.