UNPKG

@ketch-in/packet

Version:
59 lines 1.72 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); class Observable { constructor() { this.isDestroy = false; this.events = {}; this.idObservable = Math.random().toPrecision(1); } log(...args) { console.log(`[${this.idObservable}] > `, ...args); } emit(type, ...args) { this.log(this.isDestroy); if (typeof type !== "string" || !this.events[type] || this.isDestroy) { return; } this.events[type].forEach((func) => { if (typeof func === "function") { func(this, ...args); } }); } getDestroy() { return this.isDestroy; } destroy() { this.log("destroy", this.isDestroy); const keys = Object.keys(this.events); keys.forEach((key) => { delete this.events[key]; }); this.isDestroy = true; } addEventListener(type, listener) { if (typeof type !== "string" || this.isDestroy) { return; } if (!this.events[type]) { this.events[type] = []; } if (this.events[type].includes(listener)) { return; } this.events[type].push(listener); } removeEventListener(type, listener) { if (typeof type !== "string" || !this.events[type] || !this.events[type].includes(listener)) { return; } this.events[type] = this.events[type].filter((func) => func !== listener); if (this.events[type].length === 0) { delete this.events[type]; } } } exports.default = Observable; //# sourceMappingURL=Observable.js.map