MWSE/sdk/EventTarget.js

34 lines
956 B
JavaScript

// Minimal event emitter used as a base class throughout the SDK.
// Named MWSEEventTarget to avoid collision with the browser's built-in EventTarget.
export default class MWSEEventTarget {
constructor() {
this._events = {};
this.activeScope = false;
}
emit(eventName, ...args) {
const listeners = this._events[eventName];
if (listeners) {
for (const cb of listeners) cb(...args);
}
}
on(eventName, callback) {
if (this._events[eventName]) {
this._events[eventName].push(callback);
} else {
this._events[eventName] = [callback];
}
}
// scope(f) fires f immediately when already in scope, otherwise queues it for
// the next 'scope' event — same convenience the original TS SDK provided.
scope(f) {
if (this.activeScope) {
f();
} else {
this.on('scope', f);
}
}
}