mirror of
https://github.com/ueberdosis/tiptap.git
synced 2024-12-15 11:09:01 +08:00
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:
parent
364c744cef
commit
676ce7d9f1
@ -10,7 +10,6 @@ export default class Emitter {
|
|||||||
return this
|
return this
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
emit(event, ...args) {
|
emit(event, ...args) {
|
||||||
this._callbacks = this._callbacks || {}
|
this._callbacks = this._callbacks || {}
|
||||||
const callbacks = this._callbacks[event]
|
const callbacks = this._callbacks[event]
|
||||||
@ -22,33 +21,22 @@ export default class Emitter {
|
|||||||
return this
|
return this
|
||||||
}
|
}
|
||||||
|
|
||||||
// Remove event listener for given event. If fn is not provided, all event
|
// Remove event listener for given event.
|
||||||
// listeners for that event will be removed. If neither is provided, all
|
// If fn is not provided, all event listeners for that event will be removed.
|
||||||
// event listeners will be removed.
|
// If neither is provided, all event listeners will be removed.
|
||||||
off(event, fn) {
|
off(event, fn) {
|
||||||
if (!this._callbacks || (arguments.length === 0)) {
|
|
||||||
|
if (!arguments.length) {
|
||||||
this._callbacks = {}
|
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
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user