emitter.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import EventEmitter from 'eventemitter3';
  2. import instances from './instances';
  3. import logger from './logger';
  4. const debug = logger('quill:events');
  5. const EVENTS = ['selectionchange', 'mousedown', 'mouseup', 'click'];
  6. EVENTS.forEach(eventName => {
  7. document.addEventListener(eventName, (...args) => {
  8. Array.from(document.querySelectorAll('.ql-container')).forEach(node => {
  9. const quill = instances.get(node);
  10. if (quill && quill.emitter) {
  11. quill.emitter.handleDOM(...args);
  12. }
  13. });
  14. });
  15. });
  16. class Emitter extends EventEmitter {
  17. constructor() {
  18. super();
  19. this.listeners = {};
  20. this.on('error', debug.error);
  21. }
  22. emit(...args) {
  23. debug.log.call(debug, ...args);
  24. super.emit(...args);
  25. }
  26. handleDOM(event, ...args) {
  27. (this.listeners[event.type] || []).forEach(({ node, handler }) => {
  28. if (event.target === node || node.contains(event.target)) {
  29. handler(event, ...args);
  30. }
  31. });
  32. }
  33. listenDOM(eventName, node, handler) {
  34. if (!this.listeners[eventName]) {
  35. this.listeners[eventName] = [];
  36. }
  37. this.listeners[eventName].push({ node, handler });
  38. }
  39. }
  40. Emitter.events = {
  41. EDITOR_CHANGE: 'editor-change',
  42. SCROLL_BEFORE_UPDATE: 'scroll-before-update',
  43. SCROLL_BLOT_MOUNT: 'scroll-blot-mount',
  44. SCROLL_BLOT_UNMOUNT: 'scroll-blot-unmount',
  45. SCROLL_OPTIMIZE: 'scroll-optimize',
  46. SCROLL_UPDATE: 'scroll-update',
  47. SELECTION_CHANGE: 'selection-change',
  48. TEXT_CHANGE: 'text-change',
  49. };
  50. Emitter.sources = {
  51. API: 'api',
  52. SILENT: 'silent',
  53. USER: 'user',
  54. };
  55. export default Emitter;