class EventsBus {
constructor() {
this._callbacks = {};
this._id = 1;
}
emmit(eventType, data) {
if (!this._callbacks[eventType]) {
return;
}
this._callbacks[eventType].forEach(item => item.cb(data));
}
on(type, callback) {
if (!this._callbacks[type]) {
this._callbacks[type] = [];
}
const id = this._id++;
this._callbacks[type].push({
id: id,
cb: callback,
});
return { id, type: type };
}
revoke(prop) {
const { type, id } = prop;
if (!this._callbacks[type]) return;
const index = this._callbacks[type].findIndex(item => item.id === id);
if (index !== -1) {
this._callbacks[type].splice(index, 1);
}
}
}
const bus = new EventsBus();
bus.on('hello', (data) => console.log('hello', data));
const evt1 = bus.on('boom', (data) => console.log('boom1', data));
const evt2 = bus.on('boom', (data) => console.log('boom2', data));
const evt3 = bus.on('boom', (data) => console.log('boom3', data));
bus.revoke(evt1);
bus.emmit('boom', 42);
bus.emmit('hello', '!!!');