@rill/delegate

5.0.0 • Public • Published

Rill
@rill/delegate
API stability Standard NPM version Downloads Gitter Chat

Isomorphic event delegation utility for Rill. This allows for isomorphic DOM event binding with any templating language.

Installation

Npm

npm install @rill/delegate

API

delegate(options)

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())

delegate.on(event, [selector=document], handler)

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 => ...)
})

delegate.once(event, [selector=document], handler)

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) => ...)
});

Contributions

  • Use npm test to run tests.

Please feel free to create a PR!

Package Sidebar

Install

npm i @rill/delegate

Weekly Downloads

22

Version

5.0.0

License

MIT

Last publish

Collaborators

  • dylanpiercey