Delegate function built with ES6
npm install es6-delegateSimple, flexible function used for delegating events in JavaScript.
```
yarn add es6-delegate
Then import into a javascript file you want to use it in:
`js`
import delegate from 'es6-delegate';
* elements {String|Node|NodeList} - String, Node, or NodeList to bind the actual event to'.container'
* e.g. , document, document.querySelectorAll('.form')eventListeners {String}
* - Space separated list of events'click'
* e.g. , 'click focus'selector {String|Node|NodeList}
* - String, Node, or NodeList used to determine if the event should be triggered'.btn'
* e.g. , document.getElementById('btn1'), document.querySelectorAll('.btn')callback {Function}
* - Function called when event is triggered(event, element) => { console.log(event, element) }
* e.g
js
delegate('click', '.btn', (e, ele) => {
// Event object
const eventObj = e;
// Element that triggered event - '.btn'
const targetElement = ele;
// Array of Elements that event is bound to - [document]
const boundElement = e.relatedElements;
});
`$3
`js
delegate('.container', 'click', '.btn', (e, ele) => {
// ele is NodeList of '.btn'
// e.relatedElements is Array of '.container' elements
});
`$3
`js
const body = document.body;
delegate(body, 'click', '.btn', (e, ele) => {
// e.relatedElements is Array of 'body' elements
});
`$3
`js
const forms = document.querySelectorAll('.form');
delegate(forms, 'click', '.btn', (e, ele) => {
// e.relatedElements is array of forms
});
`$3
`js
delegate('click focus', '.btn', () => {
// Function will fire when a '.btn' is clicked or focused
});
`$3
`js
delegate('click', '.btn', (e, ele) => {
// ele will be the '.btn' that was clicked
});
`$3
`js
const btn1 = document.getElementById('btn1');
delegate('click', btn1, (e, ele) => {
// ele is btn1
});
`$3
`js
const allBtns = document.querySelectorAll('.btn');
delegate('click', allBtns, (e, ele) => {
// ele is button clicked from allBtns
});
`Unbinding Events
The delegate function returns the method it bound the event with for ease of use when unbinding events.`js
// Bind method
const method = delegate('click', '.btn', (e, ele) => {});// Unbind method
document.removeEventListener('click', method, true);
``