Debian Codegraph @

delegate/src/delegate.js

raw
1 var closest = require('./closest');
2
3 /**
4 * Delegates event to a selector.
5 *
6 * @param {Element} element
7 * @param {String} selector
8 * @param {String} type
9 * @param {Function} callback
10 * @param {Boolean} useCapture
11 * @return {Object}
12 */
13 function _delegate(element, selector, type, callback, useCapture) {
14 var listenerFn = listener.apply(this, arguments);
15
16 element.addEventListener(type, listenerFn, useCapture);
17
18 return {
19 destroy: function() {
20 element.removeEventListener(type, listenerFn, useCapture);
21 }
22 }
23 }
24
25 /**
26 * Delegates event to a selector.
27 *
28 * @param {Element|String|Array} [elements]
29 * @param {String} selector
30 * @param {String} type
31 * @param {Function} callback
32 * @param {Boolean} useCapture
33 * @return {Object}
34 */
35 function delegate(elements, selector, type, callback, useCapture) {
36 // Handle the regular Element usage
37 if (typeof elements.addEventListener === 'function') {
38 return _delegate.apply(null, arguments);
39 }
40
41 // Handle Element-less usage, it defaults to global delegation
42 if (typeof type === 'function') {
43 // Use `document` as the first parameter, then apply arguments
44 // This is a short way to .unshift `arguments` without running into deoptimizations
45 return _delegate.bind(null, document).apply(null, arguments);
46 }
47
48 // Handle Selector-based usage
49 if (typeof elements === 'string') {
50 elements = document.querySelectorAll(elements);
51 }
52
53 // Handle Array-like based usage
54 return Array.prototype.map.call(elements, function (element) {
55 return _delegate(element, selector, type, callback, useCapture);
56 });
57 }
58
59 /**
60 * Finds closest match and invokes callback.
61 *
62 * @param {Element} element
63 * @param {String} selector
64 * @param {String} type
65 * @param {Function} callback
66 * @return {Function}
67 */
68 function listener(element, selector, type, callback) {
69 return function(e) {
70 e.delegateTarget = closest(e.target, selector);
71
72 if (e.delegateTarget) {
73 callback.call(element, e);
74 }
75 }
76 }
77
78 module.exports = delegate;