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
58 lines (57 loc) • 1.96 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.delegateHandler = void 0;
const isEventTarget_1 = __importDefault(require("./isEventTarget"));
const on_1 = __importDefault(require("./on"));
const off_1 = __importDefault(require("./off"));
const matches_1 = __importDefault(require("./matches"));
/**
* Creates a function that triggers the given handler if the current event target
* matches the given selector
*
* @param selector - CSS Selector that matches the element to delegate the event to
* @param handler - Handler to trigger if selector selector match
* @return The delegate event handler
*
* @example
*
* ```ts
* const handler = delegateHandler('.my-element', (e: Event) => {});
* document.addEventHandler('click', handler);
* ```
*/
function delegateHandler(selector, handler) {
const cb = 'handleEvent' in handler
? handler.handleEvent
: handler;
return (e) => {
let target = e.target;
while (target && !matches_1.default(target, selector)) {
const parent = target.parentElement;
if (!parent) {
return;
}
target = parent;
}
const evt = e;
evt.delegateTarget = target;
return cb.call(target, evt);
};
}
exports.delegateHandler = delegateHandler;
function delegate(target, eventNames, selector, handler, options) {
if (!isEventTarget_1.default(target)) {
options = handler;
handler = selector;
selector = eventNames;
eventNames = target;
target = document;
}
const delHandler = delegateHandler(selector, handler);
on_1.default(target, eventNames, delHandler, options);
return () => off_1.default(target, eventNames, delHandler);
}
exports.default = delegate;