Add event utils

This commit is contained in:
atomiks
2018-01-05 23:33:48 +11:00
parent 6e610f15e7
commit 4f727a59bc
3 changed files with 43 additions and 0 deletions

16
snippets/off.md Normal file
View 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
View 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
```

View File

@ -108,6 +108,8 @@ negate:logic
nthElement:array nthElement:array
objectFromPairs:object objectFromPairs:object
objectToPairs:object objectToPairs:object
off:browser
on:browser
once:function once:function
onUserInputChange:browser onUserInputChange:browser
orderBy:object orderBy:object