-
Notifications
You must be signed in to change notification settings - Fork 239
/
event-handling.js
80 lines (67 loc) · 2.16 KB
/
event-handling.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/**
* Event Handling in Vanilla JS
*
* @Reference:
* http://gomakethings.com/ditching-jquery/#event-listeners
* http://www.quirksmode.org/dom/events/index.html
* http://www.jstips.co/en/DOM-event-listening-made-easy/
*/
var elem = document.querySelector('.some-class');
elem.addEventListener('click', function (e) {
// Do stuff
}, false); // the final param, `useCapture` indicates that the user wishes to initiate capture.
// Passing multiple variables to event handlers
var elem = document.querySelector('.some-class');
var someFunction = function (var1, var2, var3, event) {
// do stuff
};
elem.addEventListener('click', someFunction.bind(null, var1, var2, var3), false);
elem.addEventListener('mouseover', someFunction.bind(null, var1, var2, var3), false);
// Delegate events to the document.
var eventHandler = function () {
// Get clicked element
var toggle = event.target;
// If clicked element is the one you're looking for, run your methods
if (toggle.hasAttribute('data-example') || toggle.classList.contains('sample-class')) {
event.preventDefault(); // Prevent default click event
someMethod();
}
};
document.addEventListener('click', eventHandler, false);
// Better delegate function
function delegate(criteria, listener) {
return function (e) {
var el = e.target;
do {
if (!criteria(el)) {
continue;
}
e.delegateTarget = el;
listener.call(this, e);
return;
} while ((el = el.parentNode));
};
}
// Handle click function - ES6
function handleEvent(eventName, {onElement, withCallback, useCapture = false} = {}, thisArg) {
const element = onElement || document.documentElement;
function handler(event) {
if (typeof withCallback === 'function') {
withCallback.call(thisArg, event)
}
}
handler.destroy = function () {
return element.removeEventListener(eventName, handler, useCapture)
};
element.addEventListener(eventName, handler, useCapture);
return handler;
}
// Anytime you need
const handleClick = handleEvent('click', {
onElement: element,
withCallback: (event) => {
console.log('Tada!')
}
});
// And anytime you want to remove it
handleClick.destroy();