80fc11e5a7abdf43afc3f373cf3b9fff88012e1f128c8c351b75abb8365d706df0ab26e0d58a66cab49242fce91a7b7a157073e7db44d48e1a1b9a80b37efb 2.3 KB

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