add custom event emitter

This commit is contained in:
Philipp Kühn
2020-04-01 21:15:23 +02:00
parent c60ad0f107
commit dc98409bab
4 changed files with 47 additions and 4 deletions

View File

@@ -15,7 +15,6 @@
"@types/prosemirror-dropcursor": "^1.0.0",
"@types/prosemirror-gapcursor": "^1.0.1",
"collect.js": "^4.20.3",
"events": "^3.1.0",
"prosemirror-commands": "^1.1.3",
"prosemirror-dropcursor": "^1.3.2",
"prosemirror-gapcursor": "^1.1.4",

View File

@@ -1,4 +1,3 @@
import { EventEmitter } from 'events'
import { EditorState, TextSelection } from 'prosemirror-state'
import { EditorView} from 'prosemirror-view'
import { Schema, DOMParser, DOMSerializer } from 'prosemirror-model'
@@ -19,6 +18,7 @@ import getSchemaTypeByName from './utils/getSchemaTypeByName'
import ExtensionManager from './ExtensionManager'
import Extension from './Extension'
import Node from './Node'
import EventEmitter from './EventEmitter'
type EditorContent = string | JSON | null
type Command = (next: Function, editor: Editor, ...args: any) => any
@@ -73,7 +73,9 @@ export class Editor extends EventEmitter {
const command = this.commands[name]
if (!command) {
throw new Error(`tiptap: command '${name}' not found.`)
// TODO: prevent vue devtools to throw error
// throw new Error(`tiptap: command '${name}' not found.`)
return
}
return (...args: any) => command(...args)

View File

@@ -0,0 +1,42 @@
export default class EventEmitter {
_callbacks: { [key: string]: Function[] } = {}
on(event: string, fn: Function) {
if (!this._callbacks[event]) {
this._callbacks[event] = []
}
this._callbacks[event].push(fn)
return this
}
emit(event: string, ...args: any) {
const callbacks = this._callbacks[event]
if (callbacks) {
callbacks.forEach(callback => callback.apply(this, args))
}
return this
}
off(event: string, fn?: Function) {
const callbacks = this._callbacks[event]
if (callbacks) {
if (fn) {
this._callbacks[event] = callbacks.filter(callback => callback !== fn)
} else {
delete this._callbacks[event]
}
}
return this
}
removeAllListeners() {
this._callbacks = {}
}
}