From 676ce7d9f1a76cbc1de274a70a2394408f5867f0 Mon Sep 17 00:00:00 2001 From: "GIL B. Chan" Date: Wed, 8 May 2019 15:01:21 +0900 Subject: [PATCH] refactor src/Utils/Emitter.js - Make flow of logic more compact. It reduces 12 code lines. - Use filter for simple element removal. Unless there are lots of elements, breaking a loop doesn't actually have practical benefit. - More flexible. It would be easier to edit even if argument is changed to option pack (json). --- packages/tiptap/src/Utils/Emitter.js | 40 ++++++++++------------------ 1 file changed, 14 insertions(+), 26 deletions(-) diff --git a/packages/tiptap/src/Utils/Emitter.js b/packages/tiptap/src/Utils/Emitter.js index 5fa5a36e5..23a2dd32a 100644 --- a/packages/tiptap/src/Utils/Emitter.js +++ b/packages/tiptap/src/Utils/Emitter.js @@ -10,7 +10,6 @@ export default class Emitter { return this } - emit(event, ...args) { this._callbacks = this._callbacks || {} const callbacks = this._callbacks[event] @@ -22,33 +21,22 @@ export default class Emitter { return this } - // Remove event listener for given event. If fn is not provided, all event - // listeners for that event will be removed. If neither is provided, all - // event listeners will be removed. + // Remove event listener for given event. + // If fn is not provided, all event listeners for that event will be removed. + // If neither is provided, all event listeners will be removed. off(event, fn) { - if (!this._callbacks || (arguments.length === 0)) { + + if (!arguments.length) { this._callbacks = {} - return this - } - - // specific event - const callbacks = this._callbacks[event] - if (!callbacks) { - return this - } - - // remove all handlers - if (arguments.length === 1) { - delete this._callbacks[event] - return this - } - - // remove specific handler - for (let i = 0; i < callbacks.length; i += 1) { - const callback = callbacks[i] - if (callback === fn) { - callbacks.splice(i, 1) - break + } else { + // event listeners for the given event + const callbacks = this._callbacks ? this._callbacks[event] : null + if (callbacks) { + if (fn) { + this._callbacks[event] = callbacks.filter(cb => cb !== fn) // remove specific handler + } else { + delete this._callbacks[event] // remove all handlers + } } }