Isomorphic event delegation utility for Rill. This allows for isomorphic DOM event binding with any templating language.
npm install @rill/delegate
Setups up a middleware that will reset event listeners once per request. This allows for page specific delegators.
const app = require('rill')()
const delegate = require('@rill/delegate')
// Setup middleware.
app.use(delegate())
Registers a delegated event listener for the request.
app.get('/', (ctx) => {
// Here we listen for `keyup` events that match a `.verification-code` element.
delegate.on('keyup', '.verification-code', (ev, go) => {
// `currentTarget` will be the element that matched the selector.
const input = ev.currentTarget;
const code = input.value
// The second argument is the 'go' utility, which is much like native fetch but tells Rill to navigate.
if (code.length === 5) {
// In this case when we have 5 characters, we navigate to the submission page.
go('/submit', {
method: 'POST',
body: { code }
})
}
})
// We can also add event listeners to the window by omitting the selector.
delegate.on('scroll', ev => ...)
// Finally, #on returns a function which can be used to stop the listener.
const cancel = delegate.on('scroll', ev => ...)
})
Registers a delegated event listener for the request that is canceled after the first run.
app.get('/', (ctx) => {
// Scroll will only fire at most once per request.
const cancel = delegate.once('scroll', (ev, go) => ...)
});
- Use
npm test
to run tests.
Please feel free to create a PR!