1 | const createEventHub = () => ({
|
2 | hub: Object.create(null),
|
3 | emit(event, data) {
|
4 | (this.hub[event] || []).forEach(handler => handler(data));
|
5 | },
|
6 | on(event, handler) {
|
7 | if (!this.hub[event]) this.hub[event] = [];
|
8 | this.hub[event].push(handler);
|
9 | },
|
10 | off(event, handler) {
|
11 | const i = (this.hub[event] || []).findIndex(h => h === handler);
|
12 | if (i > -1) this.hub[event].splice(i, 1);
|
13 | },
|
14 | clear(keys) {
|
15 | if (keys) {
|
16 | for (let key of [].concat(keys)) {
|
17 | this.hub[key] = [];
|
18 | }
|
19 | } else {
|
20 | this.hub = Object.create(null);
|
21 | }
|
22 | },
|
23 | });
|
24 |
|
25 | export default createEventHub;
|