A better way to manage DOM event delegation and handling
npm install receptor> Event delegation is a method for listening for events that bubble to
> a higher level in the DOM and applying a function only if the event's
> target meets some criteria (typically that it matches a given CSS
> selector). The primary advantage over adding event listeners to
> specific elements is that **you don't need to know what's in the DOM
> to listen for events from certain elements.** In other words, you can
> modify the DOM willy-nilly without having to juggle adding and
> removing "direct" event listeners whenever certain elements are
> added and removed.
There are [lots of different tools][other tools] that do delegation.
The technique is even baked into jQuery,
which behaves "correctly" in the sense that delegated functions match
CSS selectors both for the target element _and its ancestors_.
š„ The big difference between receptor and other tools is that it offers
functional, declarative methods for "routing" events via different
selectors and keyboard keys,
ignoring subtrees of the DOM, adding one-off
listeners, and crafting reuseable behaviors.
``sh`
npm install receptor
In CommonJS environments, you may either require the module and access its
API via the top-level export:
`js`
const receptor = require('receptor');
const click = receptor.delegate('click', 'button', function(e) {
// ...
});
...or, if you're using ES2015 and/or [tree-shaking], you can import the
top-level API methods directly:
`js`
import {behavior, delegateAll} from 'receptor';
// etc.
callback if
the event target matches the given CSS selector, _or if it is
contained by an element that does_. The callback is called with the
matching element as this.Why? Because many delegation tools only handle the case in which
the event's
target matches the given selector, which breaks down
as soon as you want to delegate to elements with children.`html
`$3
Returns a delegated function that treats each key in the selectors
map as a CSS selector to match _a la_ receptor.delegate(), and can either
delegate events to multiple callbacks with matching selectors or
short-circuit delegation to later selectors by returning false:`html
``[key name]: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key
[other tools]: https://www.npmjs.com/search?q=delegate
[addEventListener]: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
[webpack]: https://webpack.github.io/
[browserify]: http://browserify.org/
[rollup]: https://rollupjs.org/
[tree-shaking]: https://webpack.js.org/guides/tree-shaking/