Initial commit — Meridian OS browser desktop demo
This commit is contained in:
36
js/core/bus.js
Normal file
36
js/core/bus.js
Normal file
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* Simple pub/sub event bus.
|
||||
* on(evt, cb) - subscribe
|
||||
* emit(evt, data) - publish
|
||||
*/
|
||||
const Bus = (() => {
|
||||
const listeners = new Map();
|
||||
|
||||
return {
|
||||
on(evt, cb) {
|
||||
if (!listeners.has(evt)) listeners.set(evt, new Set());
|
||||
listeners.get(evt).add(cb);
|
||||
return () => this.off(evt, cb);
|
||||
},
|
||||
|
||||
off(evt, cb) {
|
||||
const set = listeners.get(evt);
|
||||
if (set) {
|
||||
set.delete(cb);
|
||||
if (set.size === 0) listeners.delete(evt);
|
||||
}
|
||||
},
|
||||
|
||||
emit(evt, data) {
|
||||
const set = listeners.get(evt);
|
||||
if (set) {
|
||||
for (const cb of set) {
|
||||
try { cb(data); } catch (e) { console.error(`Bus emit error (${evt}):`, e); }
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
})();
|
||||
|
||||
export default Bus;
|
||||
export { Bus };
|
||||
Reference in New Issue
Block a user