Normalizing the CodeMirror OnKeyEvent with jQuery

爱⌒轻易说出口 提交于 2019-12-12 16:15:15

问题


I'm using CodeMirror along with jQuery to provide syntax highlighting on a pet PoC project. It's been doing great, until I realized that CodeMirror seems to be capturing key press events on the DOM in such a way that it stops global application hotkeys from working when I'm currently typing into a CM-enabled textarea.

For simplicity's sake, let's assume that I have the following listener on my page:

var hotkey = function (e) {
    if (e.shiftKey) { alert('foo'); }
};
$(document).keypress(hotkey);

This would work everywhere in the page, except when I have a CM textarea in focus.

To try to get around this, I tried utilizing CM's onKeyEvent option, along with attempting to normalize the event object being passed by CM's handler with jQuery.Event like so:

var cm = CodeMirror.fromTextArea(someTextArea, {
    onKeyEvent : function (editor, event) {
        hotkey($.Event(event));
    }
});

This successfully gets the keydown and keypress events over on to my hotkey handler.

The problem is, the "normalized" event object doesn't seem to be normalized enough, as referencing something trivial as e.shiftKey in the hotkey scope returns undefined. (I do get e.type correctly as either keydown or keypress though, so I know I'm passing in an event object.)

Is there anything I'm missing here that's causing my event to have missing properties, or am I just screwed?

I could definitely just double back and access raw event properties, but, hey, I'd really love to be able to utilize jQuery-normalized objects as much as the next guy most anywhere I need to (and browser-agnosticism is just the start of it).


回答1:


$.Event is for creating custom events, i.e. to trigger them on your own later. You want $.event.fix.

var cm = CodeMirror.fromTextArea(someTextArea, {
    onKeyEvent : function (editor, e) {
        hotkey($.event.fix(e));
    }
});


来源:https://stackoverflow.com/questions/5902683/normalizing-the-codemirror-onkeyevent-with-jquery

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