CoffeeScript parent class reference with jQuery callback

I am new to CoffeScript, and I was wondering if there is a way to write the following code snippet without referencing the global variable application:

class App constructor: -> @ui = ui.init() $('#content-holder a[rel!=dialog]').live 'click', -> link = $(@).attr 'href' app.loadUrl link return false loadUrl: (href) -> # ... app = new App() 

Using the fat arrow does not work, since then I lose the reference to the jQuery object, i.e.

 class App constructor: -> @ui = ui.init() $('#content-holder a[rel!=dialog]').live 'click', => # @ now references App link = $(@).attr 'href' this.loadUrl link return false loadUrl: (href) -> # ... 

The first code snippet works, but I want to get rid of the global variable if possible :-)

Cheers, Gaz.

+6
source share
2 answers

Your click handler receives the event that took place in ... so you can get the best of both worlds using the bold arrow without requiring the self link too:

 constructor: -> @ui = ui.init() $('#content-holder a[rel!=dialog]').live 'click', (e) => link = $(e.target).attr 'href' @loadUrl link return false 
+10
source

Well, CS is just a higher level syntax for JS.

In JS, this can only refer to one object.

The thick arrow uses closure to make this equal to a higher level of this , and more, and why it overrides this in the callback area

A simple arrow, in contrast, is simply an alias for function , and therefore this is a DOM element in the first case.

Finally, @something translates trivially to this.something and does nothing.

So my opinion is that your best bet is really making self = @ before binding.

+5
source

Source: https://habr.com/ru/post/898990/


All Articles