“addEventListener”在幕后如何工作? [关闭]

2024-02-25

所以,我有这种好奇心已经有一段时间了。我想知道,如何addEventListener在幕后工作。我知道它的作用,但我就是不明白它是如何做到的。

我检查了很多链接和资源this https://stackoverflow.com/questions/33914044/how-does-addeventlistener-work-under-the-hood是最接近我正在寻找的但仍然没有成功的。

为了澄清我真正想要的是什么,我想知道如何创建自己的addEventListener函数将第一个参数作为事件名称,第二个参数作为接受事件的回调eventArgs争论。


这是事件调度系统的简单示例

class BusEvent {
    eventName = null;
    callbacks = [];

    constructor(eventName) {
        this.eventName = eventName;
    }

    register(callback) {
        this.callbacks.push(callback);
    }

    unregister(callback) {
        const index = this.callbacks.indexOf(callback);
        if (index > -1) {
            this.callbacks.splice(index, 1);
        }
    }

    execute(data) {
        const callbacks = this.callbacks.slice(0);
        callbacks.forEach((callback) => {
            callback(data);
        });
    }
}

class MessageBus {
    constructor() {
        this.events = {};
    }

    dispatch(eventName, data) {
        const event = this.events[eventName];
        if (event) {
            event.execute(data);
        }
    }

    on(eventName, callback) {
        let event = this.events[eventName];
        if (!event) {
            event = new BusEvent(eventName);
            this.events[eventName] = event;
        }
        event.register(callback);
    }

    off(eventName, callback) {
        const event = this.events[eventName];
        if (event && event.callbacks.indexOf(callback) > -1) {
            event.unregister(callback);
            if (event.callbacks.length === 0) {
                delete this.events[eventName];
            }
        }
    }
}

Usage:

const messageBus = new MessageBus();
messageBus.on('ReceiveData', (data) => {
    console.log(data);
})

messageBus.dispatch('ReceiveData', { name: 'Ted' });
// console logs { name: 'Ted' }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

“addEventListener”在幕后如何工作? [关闭] 的相关文章

随机推荐