shared-event-listeners
v0.1.2
Published
A utility for minimising the number of event listeners bound on a given DOM element.
Downloads
17
Maintainers
Readme
shared-event-listeners
A utility for minimising the number of event listeners bound on a given DOM element.
Example
import sharedEventListeners from 'shared-event-listeners';
const button = document.querySelector('.button');
const eventListeners = sharedEventListeners(button);
function foo() {
console.log('foo');
}
const removeFooListener = eventListeners.add('click', foo);
function bar() {
console.log('bar');
}
const removeBarListener = eventListeners.add('click', bar);
Both the foo
and bar
listeners are called when we click on the .button
. However, only one event listener is actually bound on the .button
. (Internally, said event listener calls foo
and bar
in turn on the click
event.)
Each call to add
returns a function for removing the particular listener. In our example, the one event listener that was bound will be removed after we call both removeFooListener
and removeBarListener
.
removeFooListener();
removeBarListener();
Run the example:
$ git clone https://github.com/yuanqing/shared-event-listeners
$ npm install
$ npm install --global gulp
$ gulp example --open
API
import sharedEventListeners from 'shared-event-listeners';
const eventListeners = sharedEventListeners([element])
element
— A DOM element. Defaults towindow
.
eventListeners.add(eventName, listener)
Analogous to calling addEventListener
. Returns a function for removing the listener.
eventName
— A string.listener
— A function that is called when an event of the specifiedeventName
occurs.
eventListeners.remove(eventName, listener)
Analogous to calling removeEventListener
.
eventName
— A string.listener
— The function to be removed.
Installation
Install via npm:
$ npm i --save shared-event-listeners