@getModel() vs atom.workspace.getActiveTextEditor()


#1

Hi everybody!

I have a doubt regarding the use of @getModel() vs atom.workspace.getActiveTextEditor().

Apart from the obvious (the first one cannot be used if you don’t have a this pointing to a suitable target, the second one will return '' if the current active item in the workspace is not an editor), is there any reason why to choose one over the other when both may work?

For example, in the following code both options can be used:

atom.commands.add 'atom-text-editor', 'new-command', ->
    editor_thru_getModel = @getModel()
    editor_thru_getActiveTextEditor = atom.workspace.getActiveTextEditor()
    if editor_thru_getModel == editor_thru_getActiveTextEditor
        console.log "They're the same!"

The code above outputs They're the same!, as expected. So, why using one or the other in such contexts? Is there any risk of this being shadowed there?

Thanks a lot in advance and my excuses for the weird question. I’m new to Atom, Coffeescript, etc.


#2

My second line of a command is usually return unless editor = atom.workspace.getActiveTextEditor() to say, “If you somehow got here without an active TextEditor, please do nothing.” I don’t use it because I think it’s particularly necessary, but because it’s an elegant way to cover my ass.

I honestly don’t know and doubt it.


#3

Thanks for the reply, @DamnedScholar (BTW, funny nick :joy: )

I do the same as you in my commands, and for the same reason. But unfortunately this doesn’t answer my question, I still don’t know if one way of getting the current editor is better than the other, except obviously in the occasions I already mentioned (if there’s no this, you can’t use @getModel()).

Thanks anyway, I’ll keep investigating, but I couldn’t find anything on Google. Maybe I’ll check Atom sources to see the difference between both ways to try to understand if one should be used over the other.

Again, thanks :slight_smile:


#4

Well, the only reason I can think of to not use a particular way is if the command ends up being run in a context where it can’t find a TextEditor and that raises a “can’t read property X of undefined” error. But if you have something like return unless in there, you quash that possibility and there’s nothing to worry about.


#5

I’ll use getActiveTextEditor() then, thanks @DamnedScholar! :slight_smile: