This repository has been archived by the owner on Sep 3, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 108
/
ClickOut.js
72 lines (60 loc) · 1.67 KB
/
ClickOut.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
/**
* @copyright 2010-2015, The Titon Project
* @license http://opensource.org/licenses/BSD-3-Clause
* @link http://titon.io
*/
import Event from 'events/Event';
import { isTouch } from 'extensions/flags';
export default class ClickOut extends Event {
/**
* Bind a global `click` (or `touchend` on touch devices) event to monitor for click outs.
*/
constructor() {
super(document);
this.elements = new Set();
// Event handlers
this.handler = this.handle.bind(this);
// Bind default events
this.enable();
}
/**
* Unbind events.
*/
disable() {
this.context.removeEventListener(isTouch ? 'touchend' : 'click', this.handler);
}
/**
* Bind events.
*/
enable() {
this.context.addEventListener(isTouch ? 'touchend' : 'click', this.handler);
}
/**
* Loop through all elements being monitored and verify that they have not been clicked.
* If so, dispatch a `clickout` event to that element.
*
* @param {Event} e
*/
handle(e) {
let target = e.target;
this.elements.forEach(element => {
if (target !== element && !element.contains(target)) {
this.dispatch('clickout', {
target: target
}, element);
}
});
}
/**
* Add an element to the list to be monitored.
*
* @param {HTMLElement|HTMLElement[]} element
*/
monitor(element) {
if (Array.isArray(element)) {
element.forEach(el => this.elements.add(el));
} else {
this.elements.add(element);
}
}
}