事件总线EventBus

Published: · LastMod: June 17, 2023 · 179 words

日常我们在vue开发的时候使用公共事件总线进行跨组建数据传递,这里我们自己封装一个事件总线,了解其背后的原理

 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
class MyEvent {
    constructor() {
        this._eventMap = new Map()
    }


    on(event, callback) {
        if(event && typeof callback == 'function') {
            this._eventMap.has(event) || this._eventMap.set(event, []);
            this._eventMap.get(event).push(callback);
        }
        return this;
    }

    off(event, callback) {
        if(event) {
            if(typeof callback == 'function') {
                const callbacks = this._eventMap.get(event) || [];
                for(let i in callbacks) {
                    if(callbacks[i] === callback) {
                        callbacks.splice(i, 1);
                    }
                }
            } else {
                this._eventMap.delete(event)
            }

        }
        return this
    }

    once(event, callback) {

    }

    emit(event, ...args) {
        if(!this._eventMap.has(event)) return false;
        this._eventMap.get(event).map(callback => callback(...args))
        return true;
    }
}