UNPKG

vanillajs-browser-helpers

Version:

Collection of convenience code snippets (helpers) that aims to make it a little easier to work with vanilla JS in the browser

37 lines (36 loc) 1.2 kB
import isEventTarget from './isEventTarget'; import eventOptionsSupported from './eventOptionsSupported'; import on from './on'; import off from './off'; const manuelOnce = (elm, handler, when) => { const offHandler = (e) => { if (when && when(e) !== true) { return true; } off(elm, e.type, offHandler); return 'handleEvent' in handler ? handler.handleEvent(e) : handler(e); }; return offHandler; }; const bind = (elm, eventNames, handler, options) => { const noOptions = !eventOptionsSupported(); const { when, ...eventOptions } = options || {}; eventOptions.once = !when; const eventHandler = when || noOptions ? manuelOnce(elm, handler, when) : handler; on(elm, eventNames, eventHandler, eventOptions); return () => off(elm, eventNames, eventHandler, eventOptions); }; function once(elm, eventNames, handler, options) { if (!isEventTarget(elm)) { options = handler; handler = eventNames; eventNames = elm; elm = document; } return bind(elm, eventNames, handler, options); } export default once;