Last active
August 7, 2018 14:32
-
-
Save yutahaga/e349eeb1f79df1462d05dddc4dfe1d3b to your computer and use it in GitHub Desktop.
Passive Event Listeners Helpers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Used to detect browser support for adding an event listener with options | |
* Credit: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener | |
*/ | |
let supportsCaptureOption = false; | |
try { | |
const opts = Object.defineProperty({}, 'capture', { | |
get() { | |
supportsCaptureOption = true; | |
}, | |
}); | |
window.addEventListener('test', null, opts); | |
} catch (e) {} /* eslint-disable-line no-empty */ | |
/** | |
* Helper to create a safety event listener options | |
* | |
*/ | |
export const createSafetyEventListenerOptions = ( | |
options?: boolean | AddEventListenerOptions | |
) => { | |
return !supportsCaptureOption && typeof options === 'object' | |
? options.capture | |
: options; | |
}; | |
/** | |
* Helper to add an event listener with an options object in supported browsers | |
*/ | |
export const addEventListenerWithOptions = ( | |
target: Element, | |
type: string, | |
listener: EventListenerOrEventListenerObject, | |
options?: boolean | AddEventListenerOptions | |
) => { | |
target.addEventListener( | |
type, | |
listener, | |
createSafetyEventListenerOptions(options) | |
); | |
}; | |
/** | |
* Helper to remove an event listener with an options object in supported browsers | |
*/ | |
export const removeEventListenerWithOptions = ( | |
target: Element, | |
type: string, | |
listener: EventListenerOrEventListenerObject, | |
options?: boolean | AddEventListenerOptions | |
) => { | |
target.removeEventListener( | |
type, | |
listener, | |
createSafetyEventListenerOptions(options) | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment