I'm new to CoffeScript and I was wondering if there's a way of writing the following piece of code without referencing the global variable app:
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 doesn't work, as then I lose 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 piece of code works, but I want to get rid of the global variable if possible :-)
Cheers, Gaz.
Your click handler gets an event passed in... so you can get the best of both worlds with the "fat arrow" without the need to also reference self
:
constructor: ->
@ui = ui.init()
$('#content-holder a[rel!=dialog]').live 'click', (e) =>
link = $(e.target).attr 'href'
@loadUrl link
return false
Well, CS is just a higher-level syntax for JS.
In JS this
can only reference a single object.
The fat arrow uses closure to make this
equal to a higher level this
, nothing more, and that's why it overrides this
in a callback's scope
The plain arrow, in contrary, is just a function
alias, and that's why this
is a DOM element in the first case.
Finally, @something
is trivially translated to this.something
, and does nothing more.
So, my opinion - your best choice is really doing self = @
before the binding.
精彩评论