forked from TooTallNate/click-outside
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.es6
66 lines (53 loc) · 1.23 KB
/
index.es6
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
/**
* Module dependencies.
*/
import ev from 'event';
import contains from 'node-contains';
/**
* Module exports.
*/
exports = module.exports = clickOutside;
exports.globalClick = globalClick;
exports.install = install;
/**
* Hash of elements and callback functions.
*/
let callbacks = new Map();
/**
* A "click outside" of a given DOM event implementation.
*
* Based off of this StackOverflow answer:
* http://stackoverflow.com/a/14188699/376773
*
* @param {Element} el - DOM element to watch for outside clicks
* @param {Function} fn - callback function to invoke when user clicks outside of `el`
* @return {Function} a function to stop watching for "click outside" events for `el`
* @api public
*/
function clickOutside (el, fn) {
callbacks.set(el, fn);
return function unbind () {
callbacks.delete(el);
};
}
/**
* Global "click" event handler.
*
* @param {Event} e
* @api private
*/
function globalClick (e) {
callbacks.forEach(function (fn, el) {
if (!contains(el, e.target)) {
// click outside
fn.call(el, e);
}
});
}
function install (doc) {
if (!doc) doc = document;
ev.bind(doc, 'click', globalClick);
}
if ('undefined' !== typeof document) {
exports.install(document);
}