使用 jQuery 标准化 CodeMirror OnKeyEvent
我使用 CodeMirror 以及 jQuery 在宠物 PoC 项目上提供语法突出显示。它一直表现出色,直到我意识到 CodeMirror 似乎正在捕获 DOM 上的按键事件,其方式是当我当前在启用 CM 的计算机中输入内容时,它会阻止全局应用程序热键工作文本区域。
为了简单起见,我们假设我的页面上有以下监听器:
var hotkey = function (e) {
if (e.shiftKey) { alert('foo'); }
};
$(document).keypress(hotkey);
这将在页面中的任何地方工作,除非我有一个焦点集中的 CM 文本区域。
为了解决这个问题,我尝试利用 CM 的 onKeyEvent 选项,并尝试使用 jQuery.Event
规范化 CM 处理程序传递的 event
对象,如下所示
var cm = CodeMirror.fromTextArea(someTextArea, {
onKeyEvent : function (editor, event) {
hotkey($.Event(event));
}
});
:将 keydown
和 keypress
事件传递到我的 hotkey
处理程序。
问题是,“标准化”event
对象似乎没有足够标准化,因为在 hotkey
中引用了诸如 e.shiftKey
之类的微不足道的东西> 范围返回未定义
。 (不过,我确实正确地将 e.type
作为 keydown
或 keypress
,所以我知道我正在传递一个 event< /code> 对象。)
这里是否缺少任何东西导致我的事件
缺少属性,或者我只是搞砸了?
我绝对可以返回并访问原始事件属性,但是,嘿,我真的很希望能够像下一个人一样在我需要的任何地方使用 jQuery 规范化对象(浏览器不可知论只是它的开始)。
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 person almost anywhere I need to (and browser-agnosticism is just the start of it).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
$.Event
用于创建自定义事件,即稍后自行触发它们。您需要$.event.fix
。$.Event
is for creating custom events, i.e. to trigger them on your own later. You want$.event.fix
.