notification.js

  1. import { queryOne } from '@ecl/dom-utils';
  2. /**
  3. * @param {HTMLElement} element DOM element for component instantiation and scope
  4. * @param {Object} options
  5. * @param {String} options.closeSelector Selector for closing the notification
  6. * @param {Boolean} options.attachClickListener Whether or not to bind click events
  7. */
  8. export class Notification {
  9. /**
  10. * @static
  11. * Shorthand for instance creation and initialisation.
  12. *
  13. * @param {HTMLElement} root DOM element for component instantiation and scope
  14. *
  15. * @return {Notification} An instance of Notification.
  16. */
  17. static autoInit(root, { NOTIFICATION: defaultOptions = {} } = {}) {
  18. const notification = new Notification(root, defaultOptions);
  19. notification.init();
  20. root.ECLNotification = notification;
  21. return notification;
  22. }
  23. constructor(
  24. element,
  25. {
  26. closeSelector = '[data-ecl-notification-close]',
  27. attachClickListener = true,
  28. } = {},
  29. ) {
  30. // Check element
  31. if (!element || element.nodeType !== Node.ELEMENT_NODE) {
  32. throw new TypeError(
  33. 'DOM element should be given to initialize this widget.',
  34. );
  35. }
  36. this.element = element;
  37. // Options
  38. this.closeSelector = closeSelector;
  39. this.attachClickListener = attachClickListener;
  40. // Private variables
  41. this.close = null;
  42. // Bind `this` for use in callbacks
  43. this.handleClickOnClose = this.handleClickOnClose.bind(this);
  44. }
  45. /**
  46. * Initialise component.
  47. */
  48. init() {
  49. if (!ECL) {
  50. throw new TypeError('Called init but ECL is not present');
  51. }
  52. ECL.components = ECL.components || new Map();
  53. this.close = queryOne(this.closeSelector, this.element);
  54. // Bind click event on close
  55. if (this.attachClickListener && this.close) {
  56. this.close.addEventListener('click', this.handleClickOnClose);
  57. }
  58. // Set ecl initialized attribute
  59. this.element.setAttribute('data-ecl-auto-initialized', 'true');
  60. ECL.components.set(this.element, this);
  61. }
  62. /**
  63. * Destroy component.
  64. */
  65. destroy() {
  66. if (this.attachClickListener && this.close) {
  67. this.close.removeEventListener('click', this.handleClickOnClose);
  68. }
  69. if (this.element) {
  70. this.element.removeAttribute('data-ecl-auto-initialized');
  71. ECL.components.delete(this.element);
  72. }
  73. }
  74. /**
  75. * Remove the notification component.
  76. */
  77. handleClickOnClose() {
  78. // IE way to remove a node...
  79. if (this.element.parentNode) {
  80. this.element.parentNode.removeChild(this.element);
  81. }
  82. return this;
  83. }
  84. }
  85. export default Notification;