I want my controllers to be able to subscribe to an external event source, which I would usually define with:
var source = new EventSource('http://someURL.com/foo');
source.addEventListener('bar', handler, false);
Now let's say that the API I'm working with has only one event proper, but that event gives you a different string depending on what actual event it is. So my handler would look something like:
var handler = function(data) {
switch(data.cmd) {
case 'alpha' : doSomething(); break;
case 'beta' : doSomethingElse(); break;
case 'cappa' : doAnotherThing(); break;
}
}
Which is unfortunate, I know, but that's the way it has been implemented. What I want is to be able to expose a service API that makes sense, so in my controllers I would be able to subscribe to each type of event individually, and subscribe once, or repeatedly, as well as unsubscribe.
Does this make sense? Is there a better way to do this that I am missing using the $q API? If not, how would I go about mapping an asynchronous event to an AngularJS service API?
You could register a listener for each message type.
source.addEventListener('alpha', function(e) {
doSomething();
}, false);
source.addEventListener('beta', function(e) {
doSomethingElse();
}, false);