0.1.3 • Published 8 years ago

dom-eventr v0.1.3

Weekly downloads
1
License
MIT
Repository
github
Last release
8 years ago

Deprecated: Use addEventListener instead

Unless

  • You like using eventr.manage to manage multiple subscriptions
  • You like the way Eventr manages scope
  • You like the way Eventr manages unsubscribes

Eventr

Eventr is a simple event callback store with hijack resistance built in.

The problem with unmanaged global DOM events is that they can be overwritten and can only have one callback fire at once. Imagine that last-year.js needed to watch the document.onkeypress event but then hype-lib.js, that is now also a dependency, also needs to listen to the onkeypress event.

Which one wins the callback war? With Eventr, they both do.

Getting Started

Install

$ npm install dom-eventr

Then include in your project.

import Eventr from 'dom-eventr';

Event Subscription

There are two ways to manage events.

Subscriptions

eventr = new Eventr;
eventr.subscribe('onclick', (e) => {
  // Will fire anytime a click happens within `document`
  // ...
});

Or with context specified

let messageTextNode = document.querySelector('textarea#message');
eventr.subscribe('onpaste', (e) => {
  // Prevent paste events while focused in the message textarea.
  e.preventDefault();
  // ...
}, messageTextNode);

Manager

Define the events that will be managed by Eventr.

eventr.manage(
  [
    // Will manage keypress events on input#username
    {
      event: 'onkeypress',
      scope: document.querySelector('input#username')
    },

    // Will manage all click events on all buttons
    {
      event: 'onclick',
      scope: document.querySelectorAll('button')
    }
  ]
);

Assign to them like you normally would.

Note: Any callbacks attached previous to this scripts initialization will be automatically subscribed.

document.querySelector('input#username').onkeypress = (e) => {
  console.log("Look, I'm key: " + e.charCode);
};

Unsubscribing

In order to stop making calls to a particular callback just return false; and it will remove that callback from the event store.

The below example will only fire once and then unsubscribe.

eventr.subscribe('onclick', (e) => {
  console.log("This is the only time you will see this message.");
  return false; // Unsubscribes
}, document.querySelector('button#someButton'));

Other Options

Blocking

let eventr = new Eventr('always');

Just pass one of the following values when initializing the class

  • never - Will auto-load previously attached callbacks and not prevent future callbacks DEFAULT
  • always - Will block all previous and new callback assignments to whatever it manages
  • previous - Disregards previous attachments
  • new - Will only deny any new reference attempts

License

MIT

0.1.3

8 years ago

0.1.2

8 years ago

0.1.1

8 years ago

0.1.0

8 years ago