Created
June 28, 2016 11:10
-
-
Save tenphi/91236fa60f631adaedd4327401677d4c to your computer and use it in GitHub Desktop.
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
(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