-
Notifications
You must be signed in to change notification settings - Fork 0
/
Emitter.js
53 lines (35 loc) · 1.26 KB
/
Emitter.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// e.g : https://github.com/Reactive-Extensions/RxJS/blob/master/doc/howdoi/eventemitter.md
import { Subject } from 'rxjs/Subject';
import { not, isNotDef, isString, isFunction, hasOwnProp } from './_util';
const createFuncName = name => `$${name}`;
class Emitter {
constructor() {
this.subjects = {};
}
emit(name, data) {
if (not(isString)(name)) throw new TypeError('Emitter: name variable type should be string.');
const _ = this,
fnName = createFuncName(name);
if (isNotDef(_.subjects[fnName])) _.subjects[fnName] = new Subject();
_.subjects[fnName].next(data);
return _;
}
listen(name, handler) {
if (not(isString)(name)) throw new TypeError('Emitter: name variable type should be string.');
if (not(isFunction)(handler)) throw new TypeError('Emitter: handler variable type should be function.');
const _ = this,
fnName = createFuncName(name);
if (isNotDef(_.subjects[fnName])) _.subjects[fnName] = new Subject();
return _.subjects[fnName].subscribe(handler);
}
dispose() {
const _ = this,
subjects = _.subjects;
for (const prop in subjects) {
if (hasOwnProp.call(subjects, prop)) subjects[prop].unsubscribe();
}
_.subjects = {};
return _;
}
}
export default Emitter;