How to listen and prevent keydown event?


Hi guys, I’ve developed a package called atom-2048 and it worked in atom 0.XX.

While trying to port it for atom 1.0, it turns out I can’t use document.addEventListener for keydown event anymore. It won’t fire.

But if I use atom.views.getView(atom.workspace).addEventListener "keydown" (e)->, the event is propagated to me, but I can’t prevent it.

So how can I fix this?


I recently wrote some code to grab key events and stop them. I didn’t use the atom api. I just listened directly to the body element.


There’s this information in the Atom Flight Manual on how keybindings work in Atom v1.x:

Maybe you could try using the built in keybinding and commands capabilities instead of addEventListener?


Thanks @leedohm , I tried to add ‘up’ to ‘atom-text-editor’, and ‘atom-workspace’

  'up': 'atom-2048:up'
  'up': 'atom-2048:up'

And registered a disposable command like this:

@disposables.add atom.commands.add 'atom-workspace', "atom-2048:up", => @up()
@disposables.add atom.commands.add 'atom-text-editor', "atom-2048:up", => @up()

But the method is not triggered… According to the document, the keydown event occurs on a focused element, it should be ‘atom-text-editor’, am I right?


Have you tried using the Keybinding Resolver (Cmd+. on OS X and Ctrl+. on other platforms)? It will show you what key Atom saw you press and the command that was triggered because of it. This may help you understand when your keybinding is being triggered or not.


Yes, I did use keybinding resolver, but my package is not in the list when I press up button. When I press up button, a ‘core:move-up’ command is sent to body.