emitter.js 1.5 KB

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