Iam new to coffescript but i iam interested what is the best way to bind events from jquery to coffeescript class instance? Iam trying to prevent having too many nested callbacks in my class:
class Page
id2clicks : 0
id3clicks : 0
id4clicks : 0
onLoad: ->
$('#id2').on 'click', @ , @onId2Click
$('#id3').on 'click', $.proxy(@onId3Click,@)
$('#id4').on 'click' , () =>
@id4clicks++
alert @id4clicks
onId2Click: (e) ->
e.data.id2clicks++
alert e.data.id2clicks
onId3Click: ->
@id3clicks++
alert @id3clicks
p = new Page()
p.onLoad()
All 3 methods works... is there any better way / recommandation to do this?
As of today, January 2020, CoffeeScript is completely dead on the market (though the GitHub repository is still kind of alive).
CoffeeScript is something that makes even good JavaScript code better. CoffeeScript compiled code can do everything that natively written JavaScript code can, only the code produced by using CoffeeScript is way shorter, and much easier to read.
Personally, I prefer this way, as it is the shortest and shows the handler in-line (notice that I also omitted the parentheses):
$('#id4').on 'click' , =>
@id4clicks++
alert @id4clicks
This is very good for short handlers. However, occasionally you have a function that you want to split out and reuse elsewhere, in which case I prefer to use something like
$('#id2').on 'click', $.proxy(@onId2Click, @)
or even
$('#id2').on 'click', (e) =>
@onId2Click e
Another way is to write
onId3Click: =>
@id3clicks++
alert @id3clicks
and use
$('#id3').on 'click', @onId3Click
But I would personally discourage this because most people don't expect @onId3Click
to be a bound function and it forces them to jump to the part of the code where it's defined to check.
CoffeeScript introduced an entire piece of syntax specifically for this problem: The fat arrow, =>
. Use it:
$('#id4').click (event) =>
@id4clicks++
alert @id4clicks
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With