From 4f727a59bcee3ec91520449638dab48bfb6d7d37 Mon Sep 17 00:00:00 2001 From: atomiks Date: Fri, 5 Jan 2018 23:33:48 +1100 Subject: [PATCH] Add event utils --- snippets/off.md | 16 ++++++++++++++++ snippets/on.md | 25 +++++++++++++++++++++++++ tag_database | 2 ++ 3 files changed, 43 insertions(+) create mode 100644 snippets/off.md create mode 100644 snippets/on.md diff --git a/snippets/off.md b/snippets/off.md new file mode 100644 index 000000000..6c3764ae0 --- /dev/null +++ b/snippets/off.md @@ -0,0 +1,16 @@ +### off + +Removes an event listener from an element. + +Use `EventTarget.removeEventListener()` to remove an event listener to an element. + +```js +const off = (el, evt, fn, opts = false) => el.removeEventListener(evt, fn, opts); +``` + +```js +// See the `on` snippet. +const fn = () => console.log('!'); +const ref = on(document.body, 'click', fn, { target: 'p' }); +off(document.body, 'click', ref); // no longer logs '!' upon clicking a `p` el child of the body +``` diff --git a/snippets/on.md b/snippets/on.md new file mode 100644 index 000000000..c8fa6ee20 --- /dev/null +++ b/snippets/on.md @@ -0,0 +1,25 @@ +### on + +Adds an event listener to an element with the ability to use event delegation. + +Use `EventTarget.addEventListener()` to add an event listener to an element. If there is a +`target` property supplied to the options object, ensure the event target matches the +target specified and then invoke the callback by supplying the correct `this` context. +Use `options` to pass options to `addEventListener` or omit it to use bubbling by default. +In order to use this function with `off`, the reference to the custom delegator function +is returned if the `target` option is specified. + +```js +const on = (el, evt, fn, opts = {}) => { + const delegatorFn = e => e.target.matches(opts.target) && fn.call(e.target, e); + el.addEventListener(evt, opts.target ? delegatorFn : fn, opts.options || false); + if (opts.target) return delegatorFn; +}; +``` + +```js +const fn = () => console.log('!'); +on(document.body, 'click', fn); // logs '!' upon clicking the body +on(document.body, 'click', fn, { target: 'p' }); // logs '!' upon clicking a `p` element child of the body +on(document.body, 'click', fn, { options: true }); // use capturing instead of bubbling +``` diff --git a/tag_database b/tag_database index dc0014097..0a8812040 100644 --- a/tag_database +++ b/tag_database @@ -108,6 +108,8 @@ negate:logic nthElement:array objectFromPairs:object objectToPairs:object +off:browser +on:browser once:function onUserInputChange:browser orderBy:object