Created
December 15, 2015 23:19
-
-
Save vogloblinsky/e4cf61817e1772cb7b21 to your computer and use it in GitHub Desktop.
AngularJS PubSub Engine
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
/*global _:false */ | |
'use strict'; | |
angular.module('PubSubEngineModule') | |
.factory('PubSubEngine', ['$q', '$rootScope', | |
function($q, $rootScope) { | |
var PubSubEngine = {}; | |
/** raise an event with a given name, returns an array of promises for each listener */ | |
PubSubEngine.publish = function(name, args) { | |
//there are no listeners | |
if (!$rootScope.$$listeners[name]) { | |
return []; | |
} | |
//setup a deferred promise for each listener | |
var deferred = [], | |
i = 0, | |
len = $rootScope.$$listeners[name].length; | |
for (i; i < len; i++) { | |
deferred.push($q.defer()); | |
} | |
//create a new event args object to pass to the | |
// $broadcast containing methods that will allow listeners | |
// to return data in an async if required | |
var eventArgs = { | |
args: args, | |
reject: function(a) { | |
deferred.pop().reject(a); | |
}, | |
resolve: function(a) { | |
deferred.pop().resolve(a); | |
} | |
}; | |
//send the event | |
$rootScope.$broadcast(name, eventArgs); | |
//return an array of promises | |
var promises = _.map(deferred, function(p) { | |
return p.promise; | |
}); | |
return promises; | |
}; | |
/** subscribe to a method, or use scope.$on = same thing */ | |
PubSubEngine.subscribe = function(name, callback) { | |
return $rootScope.$on(name, callback); | |
}; | |
/** pass in the result of subscribe to this method, or just call the method returned from subscribe to unsubscribe */ | |
PubSubEngine.unsubscribe = function(handle) { | |
if (angular.isFunction(handle)) { | |
handle(); | |
} | |
}; | |
return PubSubEngine; | |
} | |
]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment