element-plus/packages/utils/dom/event.ts
三咲智子 6503e55277
refactor(utils): migrate utils (#5949)
* refactor(utils-v2): migrate utils

* refactor(utils-v2): migrate utils

* refactor(utils-v2): migrate utils

* refactor(utils): remove

* refactor(utils): rename

* refactor(utils): move EVENT_CODE to constants

* refactor: remove generic
2022-02-11 11:03:15 +08:00

60 lines
1.5 KiB
TypeScript

/** @deprecated use `element.addEventListener` instead */
export const on = (
element: HTMLElement | Document | Window,
event: string,
handler: EventListenerOrEventListenerObject,
useCapture = false
): void => {
if (element && event && handler) {
element?.addEventListener(event, handler, useCapture)
}
}
/** @deprecated use `element.addEventListener` instead */
export const off = (
element: HTMLElement | Document | Window,
event: string,
handler: EventListenerOrEventListenerObject,
useCapture = false
): void => {
if (element && event && handler) {
element?.removeEventListener(event, handler, useCapture)
}
}
/** @deprecated use `element.addEventListener` instead */
export const once = (
el: HTMLElement,
event: string,
fn: EventListener
): void => {
const listener = function (this: any, ...args: any) {
if (fn) {
fn.apply(this, args)
}
off(el, event, listener)
}
on(el, event, listener)
}
export const composeEventHandlers = <E>(
theirsHandler?: (event: E) => boolean | void,
oursHandler?: (event: E) => void,
{ checkForDefaultPrevented = true } = {}
) => {
const handleEvent = (event: E) => {
const shouldPrevent = theirsHandler?.(event)
if (checkForDefaultPrevented === false || !shouldPrevent) {
return oursHandler?.(event)
}
}
return handleEvent
}
type WhenMouseHandler = (e: PointerEvent) => any
export const whenMouse = (handler: WhenMouseHandler): WhenMouseHandler => {
return (e: PointerEvent) =>
e.pointerType === 'mouse' ? handler(e) : undefined
}