Skip to content

Instantly share code, notes, and snippets.

@tenphi
Created June 28, 2016 11:10
Show Gist options
  • Save tenphi/91236fa60f631adaedd4327401677d4c to your computer and use it in GitHub Desktop.
Save tenphi/91236fa60f631adaedd4327401677d4c to your computer and use it in GitHub Desktop.
(function(ng) {
'use strict';
if (typeof module !== "undefined" && typeof exports !== "undefined" && module.exports === exports){
module.exports = 'tenphi.eventscope';
}
ng.module('tenphi.eventscope', [])
.factory('EventScope', () => {
let listeners = {};
class EventScope {
constructor($scope) {
if ($scope) {
this.$scope = $scope;
}
}
emit(eventName, ...args) {
if (listeners[eventName]) {
for (let listener of listeners[eventName]) {
listener(...args);
}
}
if (this.$scope) {
this.$scope.$digest();
}
return this;
}
remove(eventName, listener) {
if (listeners[eventName]) {
listeners[eventName].delete(listener);
}
return this;
}
removeAll(eventName) {
if (listeners[eventName]) {
listeners[eventName] = new Set;
}
return this;
}
on(eventName, listener) {
if (!listeners[eventName]) {
listeners[eventName] = new Set;
}
listeners[eventName].add(listener);
if (this.$scope) {
this.$scope.$on('$destroy', () => {
listeners[eventName].delete(listener);
});
}
return this;
}
}
return EventScope;
});
})(window.angular);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment