vue-hooks-plus
Version:
Vue hooks library
72 lines (71 loc) • 2.58 kB
JavaScript
var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => {
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
return value;
};
import cloneDeep from "lodash-es/cloneDeep";
import { ref, watchEffect } from "vue";
class EventEmitter {
constructor() {
__publicField(this, "subscriptions", /* @__PURE__ */ new Map());
__publicField(this, "emitEffectCache", /* @__PURE__ */ new Map());
__publicField(this, "useSubscription", (event, listener) => {
const callbackRef = ref();
watchEffect((onInvalidate) => {
var _a, _b;
callbackRef.value = listener;
function subscription(val) {
if (callbackRef.value) {
callbackRef.value(val);
}
}
const subscriptions = (_b = (_a = this.subscriptions) == null ? void 0 : _a.get(event)) != null ? _b : [];
subscriptions.push(subscription);
this.subscriptions.set(event, subscriptions);
this.emitEffect(event);
onInvalidate(() => {
this.subscriptions.delete(event);
});
});
});
__publicField(this, "emit", (event, ...args) => {
if (typeof event === "string" || typeof event === "number") {
const subscriptionValuesCallback = this.subscriptions.get(event);
subscriptionValuesCallback == null ? void 0 : subscriptionValuesCallback.forEach((callback) => {
callback == null ? void 0 : callback({
params: cloneDeep(args),
event
});
});
this.emitEffectCache.set(event, {
params: cloneDeep(args),
event
});
} else
throw new TypeError("event must be string or number !");
});
__publicField(this, "emitEffect", (event) => {
const emitEffectCache = this.emitEffectCache.get(event);
const listeners = this.subscriptions.get(event);
if (emitEffectCache)
listeners == null ? void 0 : listeners.forEach((listener) => {
listener == null ? void 0 : listener({
...emitEffectCache
});
});
});
__publicField(this, "removeListener", (event) => {
this.subscriptions.delete(event);
});
__publicField(this, "clear", () => {
this.subscriptions.clear();
});
this.clear();
}
}
const eventEmitterOverall = new EventEmitter();
export {
EventEmitter,
eventEmitterOverall
};