Skip to content

Instantly share code, notes, and snippets.

@vladimir-ivanov
Created November 20, 2015 13:27
Show Gist options
  • Save vladimir-ivanov/1715b93c47f263deb706 to your computer and use it in GitHub Desktop.
Save vladimir-ivanov/1715b93c47f263deb706 to your computer and use it in GitHub Desktop.
event emitter (dispatcher) for anuglar2 - depends on EventEmitter
import {EventEmitter} from 'angular2/angular2';
class Dispatcher {
subjects = {};
constructor() {
}
emit(topic, data = null) {
this.getInstance(topic).next(data);
}
on (topic, handler) {
this.getInstance(topic).subscribe(handler);
}
off(topic) {
if (this.subjects[topic]) {
this.subjects[topic].dispose();
delete this.subjects[topic];
}
}
dispose() {
var subjects = this.subjects;
for (let prop in subjects) {
if (subjects.hasOwnProperty(prop)) {
subjects[prop].dispose();
}
}
this.subjects = {};
}
private getInstance(topic) {
return this.subjects[topic] || (this.subjects[topic] = new EventEmitter());
}
}
export default new Dispatcher();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment