How do I add a listener from a keymap command


I have a package I want to add a command to that will listen for the next time you press the spacebar and then fire a call back and stop listening.

Currently I have this which will pick up if I am pressing keys if I place this code directly under the activate: (state) -> call, but when I place this into a custom command it does not fire. I don’t think this is the right / best way to setup a listener either so any advice or pointing in a good direction would be greatly appreciated.

atom.workspaceView.eachEditorView (editorView) ->
  editorView.on 'keypress', (event) ->
    e = editorView.getEditor()
    console.log('this ran')


A lot of that code is deprecated:

  • workspaceView can now be obtained by using atom.views.get(atom.workspace) (although you no longer need the workspaceView to achieve what you want).
  • workspaceView.eachEditorView is now workspace.observeTextEditors (editor) ->. Use atom.views.getView editor to get the editorView.
  • editorView.on no longer exists. You can use editorView.addEventListener.

Put together:

atom.workspace.observeTextEditors (editor) ->
  editorView = atom.views.getView editor
  editorView.addEventListener 'keypress', keypressHandler = (event) ->
    # do nothing unless spacebar is pressed
    return unless event.which is 32

    # remove the event listener after it's fired once
        editorView.removeEventListener keypressHandler

        # do stuff with editor or editorView