-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUseExternalClick.js
44 lines (38 loc) · 1.07 KB
/
UseExternalClick.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
export default {
beforeDestroy() {
if (typeof this.destroyExternalClickListener === "function") {
this.removeExternalClickListener();
}
},
methods: {
addExternalClickListener(
elements,
callback = null,
options = { passive: true }
) {
elements = Array.isArray(elements) ? elements : [elements];
const onClick = e => {
for (let i = 0; i < elements.length; i++) {
if (elements[i].contains(e.target)) {
return; // End early, click was internal
}
}
if (typeof callback === "function") {
callback(e);
} else {
this.$emit("external-click", e);
}
};
document.addEventListener("click", onClick, options);
this.destroyExternalClickListener = () => {
document.removeEventListener("click", onClick, options);
};
},
removeExternalClickListener() {
if (this.destroyExternalClickListener) {
this.destroyExternalClickListener();
this.destroyExternalClickListener = null;
}
}
}
};