KieSun / all-of-frontend

你想知道的前端内容都在这

Home Page:https://yuchengkai.cn/docs/frontend

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

EventBus

teefing opened this issue · comments

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

on(type, listener, ...args) {
this.events[type] = this.events[type] || [];
listener.args = [...args]
this.events[type].push(listener);
return this.off.bind(this, type, listener);
}

off(type, listener) {
if (this.events[type]) {
this.events[type] = this.events[type].filter((cb) => cb !== listener);
}
}

fire(type, ...args) {
if (this.events[type]) {
[...this.events[type]].forEach((cb) => {
cb.args = cb.args || []
const argArr = [...cb.args, ...args]
cb.call(this, ...argArr);
});
}
}

once(type, listener) {
this.events[type] = this.events[type] || [];
const proxyListener = (...args) => {
listener.call(...args)
this.off(type, proxyListener)
}
this.events[type].push(proxyListener);
}
}