Syntax sugar for events handlers. Kind of like the excellent, classnames, but for events.
$ npm install @f/event-handler
This module gives you some special syntax to make your event handlers more declarative and functional. You can create handlers for only certain keypresses, or easily attach multiple handlers to a single event.
This example calls updateText
with every keydown event, but also calls submit
only when enter is pressed:
var ev = require('@f/event-handler')
function render () {
return <input onKeyDown={ev([{enter: submit}, updateText])} />
}
You may pass an array, object, or just a plain function, and you may also do any of these things recursively. So, for instance:
var ev = require('@f/event-handler')
function render () {
return <input onKeyDown={ev[{enter: [submit, close]}, updateText]} />
}
This will close the input and submit when enter
is pressed, it will also update the text on every normal keydown.
If you rely on the return values of your handler, we have you covered. The value returned by your handlers will be returned from the constructed handler. If you've passed an array, that array will be mapped over the event, and the resulting array will be returned.
There is another syntax for specifying these handlers, which is the ability to pass pure functional decoders to transform the event before passing it in to the handler. You may specify it like this:
const select = node => node.select()
const decodeNode = e => e.target
ev({handler: select, decoder: decodeNode})
You may also declaratively specify stopPropagation: true
and preventDefault: true
. These capabilities are useful for creating more functionally pure, declarative event handlers.
descriptor
- An object, array, or function. If it's an object, the keys will be used as filters to call the handler only if the event matches the key. At the moment, the only allowed keys are keychords, though more may be forthcoming if there is interest. If an array is passed, all the functions in the array are called.
Returns: A constructed event handler that you may just pass event
to, and it will execute the handlers you've specified according to your descriptor
.
MIT