A utility for minimising the number of event listeners bound on a given DOM element.
Example
; const button = document;const eventListeners = ; { console;}const removeFooListener = eventListeners; { console;}const removeBarListener = eventListeners;
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
.
;;
Run the example:
$ git clone https://github.com/yuanqing/shared-event-listeners
$ npm install
$ npm install --global gulp
$ gulp example --open
API
;
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