封装 EventHub
class EventHub {
#events = {};
on(eventName, fn) {
this.#events[eventName] = this.#events[eventName] || [];
this.#events[eventName].push(fn);
}
emit(eventName, data) {
if (!this.#events[eventName]) return;
this.#events[eventName].map((fn) => fn.call(undefined, data));
}
off(eventName, fn) {
if (!this.#events[eventName]) return;
const index = this.#events[eventName].indexOf(fn);
if (index < 0) return;
this.#events[eventName].splice(index, 1);
}
once(eventName, fn) {
const onceFn = (data) => {
fn(data);
this.off(eventName, onceFn);
};
this.on(eventName, onceFn);
}
}
test
const eventHub = new EventHub();
const fn = (data) => console.log('click1', data);
eventHub.on('click', fn);
eventHub.on('click', (data) => console.log('click2', data));
eventHub.once('click', (data) => console.log('once', data));
eventHub.emit('click', 'hello');
eventHub.off('click', fn);
eventHub.emit('click', 'world');