How to get the editor from onDidChangeScrollLeft


#1

I have some code:

for editor in atom.workspace.getTextEditors()
  @disposables.add editor.onDidChangeScrollLeft (scrollLeft) ->
    activeEditor = atom.workspace.getActiveTextEditor()

I would like to reference the editor/view that was just scrolled. If I reference editor, it only returns the last created editor, not the current editor that was horizontally scrolled. I can use atom.workspace.getActiveTextEditor, but this only works if the user scrolls with the scroll bar. If they used the mouse wheel to scroll left/right, activeEditor is the last editor the user clicked into, not always what the mouse is controlling. I tried to reference this, but that seems to be the document or window, I couldn’t figure out it’s class. I also tried: atom.workspaceView.getActiveView(), which gives a similar result as getActiveTextEditor(). Can someone provide a little help?


#2

Rather than using atom.workspace.getTextEditors() which only gives you the TextEditors present at a certain point in time, you should probably use atom.workspace.observeTextEditors(). You can then write it this way:

atom.workspace.observeTextEditors (editor) ->
  subscription = editor.onDidChangeScrollLeft (scrollLeft) ->
    # Do something with scrollLeft here

  editor.onDidDestroy ->
    subscription.dispose()

Since you’re not iterating over anything, editor only refers to the TextEditor on which you’re creating event handlers. Also, observeTextEditors gets called once for every editor that exists or comes into existence, so you don’t have to worry about periodically updating your list.


#3

Or if you do need to do it only with the editors available at a time, you can use an immediately invoked function inside the for loop:

for editor in atom.workspace.getTextEditors()
  do (editor) ->
    # now anywhere inside this function, editor will reference the same TextEditor

#4

Thanks @leedohm and @olmokramer.

This works perfectly. I tried something like this initially, but I was doing something like:

@subscriptions.add atom.workspace.observeTextEditors
  @subscriptions.add editor.onDidChangeScrollLeft

And JavaScript didn’t like it. But, immediately adding a an observer to editor.onDidDestroy is brilliant.


#5

You probably want to add a capture of the observeTextEditors subscription so that you can dispose of it on your package’s deactivate too.


#6

Thanks, I did.