-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathmixin.js
66 lines (51 loc) · 1.6 KB
/
mixin.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
import Mixin from '@ember/object/mixin';
import { computed } from '@ember/object';
import { get } from '@ember/object';
const bound = function(fnName) {
return computed(fnName, function() {
let fn = get(this, fnName);
if (fn) { // https://github.com/zeppelin/ember-click-outside/issues/1
return fn.bind(this);
}
});
};
const supportsTouchEvents = () => {
return 'ontouchstart' in window || window.navigator.msMaxTouchPoints;
};
export default Mixin.create({
clickOutside() {},
clickHandler: bound('outsideClickHandler'),
didInsertElement() {
this._super(...arguments);
if (!supportsTouchEvents()) {
return;
}
document.body.style.cursor = 'pointer';
},
willDestroyElement() {
this._super(...arguments);
if (!supportsTouchEvents()) {
return;
}
document.body.style.cursor = '';
},
outsideClickHandler(e) {
const element = get(this, 'element');
// Check if the click target still is in the DOM.
// If not, there is no way to know if it was inside the element or not.
const isRemoved = !e.target || !document.contains(e.target);
// Check the element is found as a parent of the click target.
const isInside = element === e.target || element.contains(e.target);
if (!isRemoved && !isInside) {
this.clickOutside(e);
}
},
addClickOutsideListener() {
const clickHandler = get(this, 'clickHandler');
document.addEventListener('click', clickHandler);
},
removeClickOutsideListener() {
const clickHandler = get(this, 'clickHandler');
document.removeEventListener('click', clickHandler);
}
});