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).
This commit is contained in:
GIL B. Chan 2019-05-08 15:01:21 +09:00
parent 364c744cef
commit 676ce7d9f1

View File

@ -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
} 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
}
// 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
}
}