I created a little wrapper for one of my JavaScript libraries to enable Angular functionality. Are there any pitfalls I should be wary of with my code?
angular.module("signalR.eventAggregator", [])
.run([
"$rootScope", function($rootScope) {
function createScope(scope) {
scope.$on('$destroy', function() {
signalR.eventAggregator.unsubscribe(scope);
});
return {
subscribe: function(type, handler, constraint) {
signalR.eventAggregator.subscribe(type, function(e) {
handler(e);
if (scope.$$phase == null) {
scope.$digest();
}
}, scope, constraint);
},
publish: function(event) {
signalR.eventAggregator.publish(event);
}
}
}
$rootScope.eventAggregator = function() {
return this.__eventAggregator = this.__eventAggregator || createScope(this);
};
}
]);
More info on the code itself here.
It's used like this:
$scope.eventAggregator().subscribe(MyApp.MyEvent, onEvent);
Other scenarios it supports are
Generic events, (all events are server events proxied to javascript through a dynamic Owin javascript)
$scope.eventAggregator().subscribe(MyApp.MyGenericEvent.of("System.String"), onEvent);
Constraints, in this case listen to all events with id 5
$scope.eventAggregator().subscribe(MyApp.MyEvent, onEvent, { id: 5 });
It wraps an event-driven library, and when an event is triggered, I use digest
to update the view, and it's this part of the code that I wonder about.
handler(e);
could return a promise that I currently ignore. I tested the ng-click
directive and it also ignores any promise returned from the click handler. So at least it's consistent with the existing event handlers in Angular.