@ray-solutions/v-form-builder
Version:
Vue Form Builder PRO MAX built from top of Vue. Super dynamic and flexible including Drag and Drop feature.
55 lines (49 loc) • 1.58 kB
JavaScript
/**
* Vue 3 upgrade note:
* - Vue 2 used `new Vue()` as an event bus (with `$on/$off/$emit` and an internal `_events` map).
* - Vue 3 removed that pattern, so we provide a tiny compatible event bus here.
* - IMPORTANT: We intentionally keep the same API shape (`$on/$off/$emit` + `_events`) because
* many parts of this codebase rely on it (and even flush `_events[...] = []` in a few places).
*/
export function createEventBus() {
/** @type {Record<string, Function[]>} */
const _events = Object.create(null);
return {
_events,
/**
* Register an event handler.
* @param {string} event
* @param {Function} handler
*/
$on(event, handler) {
if (!_events[event]) _events[event] = [];
_events[event].push(handler);
return this;
},
/**
* Remove an event handler (or all handlers of an event if handler not provided).
* @param {string} event
* @param {Function=} handler
*/
$off(event, handler) {
if (!_events[event]) return this;
if (!handler) {
_events[event] = [];
return this;
}
_events[event] = _events[event].filter((h) => h !== handler);
return this;
},
/**
* Emit an event with args.
* @param {string} event
* @param {...any} args
*/
$emit(event, ...args) {
const handlers = _events[event];
if (!handlers || handlers.length === 0) return this;
handlers.slice().forEach((h) => h(...args));
return this;
},
};
}