Add event utils
This commit is contained in:
16
snippets/off.md
Normal file
16
snippets/off.md
Normal file
@ -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
|
||||
```
|
||||
25
snippets/on.md
Normal file
25
snippets/on.md
Normal file
@ -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
|
||||
```
|
||||
@ -108,6 +108,8 @@ negate:logic
|
||||
nthElement:array
|
||||
objectFromPairs:object
|
||||
objectToPairs:object
|
||||
off:browser
|
||||
on:browser
|
||||
once:function
|
||||
onUserInputChange:browser
|
||||
orderBy:object
|
||||
|
||||
Reference in New Issue
Block a user