evt-listener

EventListener, as an object.

Usage no npm install needed!

<script type="module">
  import evtListener from 'https://cdn.skypack.dev/evt-listener';
</script>

README

Build Status Coverage Status

evt-listener

What is it?

A class encapsulating an event and it's listener together.

Why would you use it?

Whenever you create an event listener and need to eventually turn it off, you would pass the same function passed to emitter.on to emitter.removeListener to do so.

Creating an EventListener (the class behind evt-listener) allows you to just call listener.off (where listener would be an instance of EventListener) without having to worry about saving and passing the event name and function. See below for a comparison.

Prerequisites

Install it using npm, saving it as a dependency.

npm i evt-listener --save

Both examples share the same event emitter boilerplate code.

var EventEmitter = require('events').EventEmitter;
var emitter = new EventEmitter();

Comparison

Without EventListener

//we have to save the event name and the listener
var eventName = 'eventName';
var listener = function(payload) {
  console.log('Event ' + eventName + ' triggered with: ' + playload);
};

emitter.on(eventName, listener);

//sometime later...
emitter.removeListener(eventName, listener);

With EventListener

var EventListener = require('evt-listener');

//create a listener
var eventNameListener = new EventListener(emitter, 'eventName');

eventNameListener.on(function(payload) {
  console.log('Event ' + eventNameListener.event + ' triggered with: ' + playload);
});

//sometime later...
eventNameListener.off();

Tips

1. Name your listeners appropriately!

2. You can chain your listener function after you create an EventListener instance.

//create a listener, giving it a handler
var eventNameListener = new EventListener(emitter, 'eventName').on(function(payload) {
  console.log('Event ' + listener.event + ' triggered with: ' + playload);
});

//same goes for once
var eventNameListener = new EventListener(emitter, 'eventName').once(function(payload) {
  console.log('Event ' + listener.event + ' triggered with: ' + playload);
});

3. Don't like using the new keyword in javascript? No worries.

var EventListener = require('evt-listener');
var listener = EventListener(emitter, 'eventName');

4. Prefer the revealing module pattern?

var EventListener = require('evt-listener').EventListener;

PS

Check out evt-emitter which adds a createListener factory method on the EventEmitter prototype. This allows you to create instances of EventListener without having to pass an emitter.