UNPKG

@stimulus-library/mixins

Version:

A library of useful controllers for Stimulus

18 lines (17 loc) 781 B
import { debounce, EventBus, wrapArray } from "@stimulus-library/utilities"; import { useMixin } from "./use_mixin"; export function useEventBus(controller, eventNameOrNames, handler, opts) { const options = opts; if (options === null || options === void 0 ? void 0 : options.debounce) { handler = debounce(handler.bind(controller), options.debounce); delete options.debounce; } else { handler = handler.bind(controller); } const eventNames = wrapArray(eventNameOrNames); const setup = () => eventNames.forEach(eventName => EventBus.on(eventName, handler)); const teardown = () => eventNames.forEach(eventName => EventBus.off(eventName, handler)); useMixin(controller, setup, teardown); return { setup, teardown }; }