Created
November 20, 2015 13:27
-
-
Save vladimir-ivanov/1715b93c47f263deb706 to your computer and use it in GitHub Desktop.
event emitter (dispatcher) for anuglar2 - depends on EventEmitter
This file contains hidden or 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
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