Source: delegate/delegate.es.js

  1. /**
  2. * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
  3. *
  4. * This library is free software; you can redistribute it and/or modify it under
  5. * the terms of the GNU Lesser General Public License as published by the Free
  6. * Software Foundation; either version 2.1 of the License, or (at your option)
  7. * any later version.
  8. *
  9. * This library is distributed in the hope that it will be useful, but WITHOUT
  10. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  11. * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
  12. * details.
  13. */
  14. /**
  15. * Checks if element is disabled or whether it exists in a disabled element tree
  16. * @param {!Element} element The DOM element to check.
  17. * @return {boolean}
  18. */
  19. function isDisabled(node) {
  20. return !!(node.disabled || node.closest('[disabled]'));
  21. }
  22. /**
  23. * Listens to the specified event on the given DOM element, but only calls the
  24. * given callback listener when it's triggered by elements that match the
  25. * given selector or target element.
  26. * @param {!Element} element The DOM element the event should be listened on.
  27. * @param {string} eventName The name of the event to listen to.
  28. * @param {string} selector Css selector that should match the event for the
  29. * listener to be triggered.
  30. * @param {!function(!Object)} callback Function to be called when the event
  31. * is triggered. It will receive the normalized event object.
  32. * @return {function} Can be used to remove the listener.
  33. */
  34. function delegate(element, eventName, selector, callback) {
  35. const eventHandler = (event) => {
  36. const {defaultPrevented, target} = event;
  37. if (defaultPrevented || (eventName === 'click' && isDisabled(target))) {
  38. return;
  39. }
  40. const delegateTarget = target.closest(selector);
  41. if (delegateTarget) {
  42. event.delegateTarget = delegateTarget;
  43. callback(event);
  44. }
  45. };
  46. element.addEventListener(eventName, eventHandler);
  47. return {
  48. dispose() {
  49. element.removeEventListener(eventName, eventHandler);
  50. },
  51. };
  52. }
  53. export default delegate;