| 1 |
// The Emitter class provides the ability to call `.on()` on Dropzone to listen |
| 2 |
// to events. |
| 3 |
// It is strongly based on component's emitter class, and I removed the |
| 4 |
// functionality because of the dependency hell with different frameworks. |
| 5 |
export default class Emitter { |
| 6 |
// Add an event listener for given event |
| 7 |
on(event, fn) { |
| 8 |
this._callbacks = this._callbacks || {}; |
| 9 |
// Create namespace for this event |
| 10 |
if (!this._callbacks[event]) { |
| 11 |
this._callbacks[event] = []; |
| 12 |
} |
| 13 |
this._callbacks[event].push(fn); |
| 14 |
return this; |
| 15 |
} |
| 16 |
|
| 17 |
emit(event, ...args) { |
| 18 |
this._callbacks = this._callbacks || {}; |
| 19 |
let callbacks = this._callbacks[event]; |
| 20 |
|
| 21 |
if (callbacks) { |
| 22 |
for (let callback of callbacks) { |
| 23 |
callback.apply(this, args); |
| 24 |
} |
| 25 |
} |
| 26 |
// trigger a corresponding DOM event |
| 27 |
if (this.element) { |
| 28 |
this.element.dispatchEvent( |
| 29 |
this.makeEvent("dropzone:" + event, { args: args }) |
| 30 |
); |
| 31 |
} |
| 32 |
return this; |
| 33 |
} |
| 34 |
|
| 35 |
makeEvent(eventName, detail) { |
| 36 |
let params = { bubbles: true, cancelable: true, detail: detail }; |
| 37 |
|
| 38 |
if (typeof window.CustomEvent === "function") { |
| 39 |
return new CustomEvent(eventName, params); |
| 40 |
} else { |
| 41 |
// IE 11 support |
| 42 |
// https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent |
| 43 |
var evt = document.createEvent("CustomEvent"); |
| 44 |
evt.initCustomEvent( |
| 45 |
eventName, |
| 46 |
params.bubbles, |
| 47 |
params.cancelable, |
| 48 |
params.detail |
| 49 |
); |
| 50 |
return evt; |
| 51 |
} |
| 52 |
} |
| 53 |
|
| 54 |
// Remove event listener for given event. If fn is not provided, all event |
| 55 |
// listeners for that event will be removed. If neither is provided, all |
| 56 |
// event listeners will be removed. |
| 57 |
off(event, fn) { |
| 58 |
if (!this._callbacks || arguments.length === 0) { |
| 59 |
this._callbacks = {}; |
| 60 |
return this; |
| 61 |
} |
| 62 |
|
| 63 |
// specific event |
| 64 |
let callbacks = this._callbacks[event]; |
| 65 |
if (!callbacks) { |
| 66 |
return this; |
| 67 |
} |
| 68 |
|
| 69 |
// remove all handlers |
| 70 |
if (arguments.length === 1) { |
| 71 |
delete this._callbacks[event]; |
| 72 |
return this; |
| 73 |
} |
| 74 |
|
| 75 |
// remove specific handler |
| 76 |
for (let i = 0; i < callbacks.length; i++) { |
| 77 |
let callback = callbacks[i]; |
| 78 |
if (callback === fn) { |
| 79 |
callbacks.splice(i, 1); |
| 80 |
break; |
| 81 |
} |
| 82 |
} |
| 83 |
|
| 84 |
return this; |
| 85 |
} |
| 86 |
} |
| 87 |
|