Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coffee script - preserve the class context and the event context

Looking for elegant solution to a common problem:

I got a class that subscribe to few events, I want the handler to be an instance method inside my class, but also want to get the event context(the element the event fired on for this case).

I'm using the fat line syntax for the method definition but got no way to get the event context. To be concrete I'm using raphael js and when subscribing on element the event object does not contain the element, only the dom element so without the event context I'll have to search the element by it's raphael id inside the paper, and I don't like it.

What is the best practice in this case? I'm currently creating a new context object before each time I subscribe to the event, the context contains the instance reference and the element reference.

like image 694
Chen Kinnrot Avatar asked Apr 12 '12 07:04

Chen Kinnrot


People also ask

Do people still use CoffeeScript?

As of today, January 2020, CoffeeScript is completely dead on the market (though the GitHub repository is still kind of alive).

What is the difference between CoffeeScript and JavaScript?

Coffeescript is an attempt to expose the good and bad parts of JavaScript in a simple easier way. The classic rule of Coffeescript is: 'It's just a plain JavaScript'. The Coffeescript code compiles one by one into the equivalent JavaScript, and there is no interpretation at the runtime.


1 Answers

If I understand you correctly you want to keep the references to both the bound and unbound contexts in the handler function. You can achieve this by manually doing something similar to what the fat arrow does:

class TheListenerObject
  constructor: ->
    context = @ # some people may call it `self`
    @theHandlerMethod = () ->
      referenceToTheListenerObjectInstance = context
      referenceToTheUnboundContext = @
like image 100
Nikita Volkov Avatar answered Sep 25 '22 14:09

Nikita Volkov