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);
}
}