Events context in Atom


#1

Hello!,

I have only some experience with CoffeeScript and this is my first approach to Atom packages, so I hope this question is not too basic. Any advice about good practices and patterns would be great also :).

I’m trying to achieve something basic. I’m running an async task, and when it finishes, I want to notify my view. event-kit seemed a good choice, as I’ve seen it has been used in several plugins. It’d be something similar to:

myClass.onSomethingHasBeenPerformed (data) ->
    @performSomethingOnTheView(data)

My problem is that when the callback is executed, the context has changed I can’t find the function performSomethingOnTheView. Javascript “this” seems to be attached to the Window main object, and I don’t really get an idea about how to get an easy access to my view, which was who called myClass.

An easy solution has been:

myClass = new MyClass(this, ...)

myClass.onDataReceived (data) ->
        data.view.performSomethingOnTheView(data.data)

In this case data is a more complex object that returns the view, that was previously supplied to the object. That does the job.

I guess that there is an easier way of doing this. I feel like I’m missing something.

Thanks a lot for your time!


#2

Use a fat arrow to create a function with a bound this:

myClass.onSomethingHasBeenPerformed (data) =>
    @performSomethingOnTheView(data)

#3

CoffeeScript has fat arrows that keep the current context. Example:

class MyClass
  constructor: ->
    globalContext = -> console.log this
    sameContext = => console.log this

    globalContext() # logs the window object
        sameContext() # logs this MyClass instance

#4

Ok…I can’t believe I missed that :scream: .

Thanks guys.


#5

That must be the most concise and succinct explanation of the fat arrow I have ever seen.
Most people try to create all kinds of complex scenarios, when this is all that’s needed.


#6

Haha, yeah I’ve done it a few times, and this is what I came up with in the end :smile: