Debian Codegraph @

good-listener/src/listen.js

raw
1 var is = require('./is');
2 var delegate = require('delegate');
3
4 /**
5 * Validates all params and calls the right
6 * listener function based on its target type.
7 *
8 * @param {String|HTMLElement|HTMLCollection|NodeList} target
9 * @param {String} type
10 * @param {Function} callback
11 * @return {Object}
12 */
13 function listen(target, type, callback) {
14 if (!target && !type && !callback) {
15 throw new Error('Missing required arguments');
16 }
17
18 if (!is.string(type)) {
19 throw new TypeError('Second argument must be a String');
20 }
21
22 if (!is.fn(callback)) {
23 throw new TypeError('Third argument must be a Function');
24 }
25
26 if (is.node(target)) {
27 return listenNode(target, type, callback);
28 }
29 else if (is.nodeList(target)) {
30 return listenNodeList(target, type, callback);
31 }
32 else if (is.string(target)) {
33 return listenSelector(target, type, callback);
34 }
35 else {
36 throw new TypeError('First argument must be a String, HTMLElement, HTMLCollection, or NodeList');
37 }
38 }
39
40 /**
41 * Adds an event listener to a HTML element
42 * and returns a remove listener function.
43 *
44 * @param {HTMLElement} node
45 * @param {String} type
46 * @param {Function} callback
47 * @return {Object}
48 */
49 function listenNode(node, type, callback) {
50 node.addEventListener(type, callback);
51
52 return {
53 destroy: function() {
54 node.removeEventListener(type, callback);
55 }
56 }
57 }
58
59 /**
60 * Add an event listener to a list of HTML elements
61 * and returns a remove listener function.
62 *
63 * @param {NodeList|HTMLCollection} nodeList
64 * @param {String} type
65 * @param {Function} callback
66 * @return {Object}
67 */
68 function listenNodeList(nodeList, type, callback) {
69 Array.prototype.forEach.call(nodeList, function(node) {
70 node.addEventListener(type, callback);
71 });
72
73 return {
74 destroy: function() {
75 Array.prototype.forEach.call(nodeList, function(node) {
76 node.removeEventListener(type, callback);
77 });
78 }
79 }
80 }
81
82 /**
83 * Add an event listener to a selector
84 * and returns a remove listener function.
85 *
86 * @param {String} selector
87 * @param {String} type
88 * @param {Function} callback
89 * @return {Object}
90 */
91 function listenSelector(selector, type, callback) {
92 return delegate(document.body, selector, type, callback);
93 }
94
95 module.exports = listen;