Re-dispatch KeyboardEvent

六眼飞鱼酱① 提交于 2019-12-13 01:09:00

问题


Working on an Angular / TypeScript app, where we have a custom basic text editor.

Trying to appropriately handle when a user has a highlighted selection and then hits a key, intending to replace the selection.

To handle this, we need to properly remove the "hidden" components that they have selected before inserting their intended content.

My initial thought was to:

  1. Capture KeyDown event
  2. Check if there is a highlighted range selected
  3. If yes, delete all of the selected content
  4. Re-dispatch the KeyDown event so it inserts the appropriate content

Here's a truncated version of our onKeyDown method:

cloneKeyboardEvent(eventToClone): KeyboardEvent {
    return new KeyboardEvent(eventToClone.type, {
        key: eventToClone.key,
        code: eventToClone.code,
        location: eventToClone.location,
        ctrlKey: eventToClone.ctrlKey,
        shiftKey: eventToClone.shiftKey,
        altKey: eventToClone.altKey,
        metaKey: eventToClone.metaKey,
        repeat: eventToClone.repeat
    });
}

onKeyDown($event: KeyboardEvent) {
    // Check if there's a selection
    if (this.isSelectionRange) {
        Helpers.stopEvent($event);

        // Delete components in selection
        this.deleteComponentsInSelection($event);

        const clonedEvent = this.cloneKeyboardEvent($event);
        document.dispatchEvent(clonedEvent);

        return true;
    }
}

Everything works up to #4.

The clonedEvent matches the original event, but it won't fire. I've inserted a debugger at the start of onKeyDown() and it only is hit once, on the initial keydown, not on the dispatchEvent().

来源:https://stackoverflow.com/questions/47060630/re-dispatch-keyboardevent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!