《简单实现自己的监听器模式》

实现监听器模式,不使用EventEmitter

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
class MyEventEmitter {
constructor() {
this.handles = Object.create(null);
}

on(evt, cb) {
if (typeof cb !== 'function') {
console.log('cb must be a function');
return;
}

if (!this.handles[evt]) {
this.handles[evt] = [];
}
this.handles[evt].push(cb);
}

emit(evt, ...args) {
if (!!this.handles[evt]) {
this.handles[evt].forEach((item) => {
Reflect.apply(item, this, args);
});
}
}
}

const emitter = new MyEventEmitter();
emitter.on('say', (name) => {
console.log('Hello, ', name);
});

setTimeout(() => {
emitter.emit('say', 'Jay');
}, 1500);
打赏
  • © 2016-2021 留叶
  • Powered by Hexo Theme Ayer
    • PV:
    • UV:

请我喝杯咖啡吧~

支付宝
微信