-
Notifications
You must be signed in to change notification settings - Fork 25
/
helpers.js
48 lines (44 loc) · 1.39 KB
/
helpers.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
/**
* querySelector wrapper
*
* @param {string} selector Selector to query
* @param {Element} [scope] Optional scope element for the selector
*/
export function qs(selector, scope) {
return (scope || document).querySelector(selector);
}
/**
* addEventListener wrapper
*
* @param {Element|Window} target Target Element
* @param {string} type Event name to bind to
* @param {Function} callback Event callback
* @param {boolean} [capture] Capture the event
*/
export function $on(target, type, callback, capture) {
target.addEventListener(type, callback, !!capture);
}
/**
* Attach a handler to an event for all elements matching a selector.
*
* @param {Element} target Element which the event must bubble to
* @param {string} selector Selector to match
* @param {string} type Event name
* @param {Function} handler Function called when the event bubbles to target
* from an element matching selector
* @param {boolean} [capture] Capture the event
*/
export function $delegate(target, selector, type, handler, capture) {
const dispatchEvent = event => {
const targetElement = event.target;
const potentialElements = target.querySelectorAll(selector);
let i = potentialElements.length;
while (i--) {
if (potentialElements[i] === targetElement) {
handler.call(targetElement, event);
break;
}
}
};
$on(target, type, dispatchEvent, !!capture);
}