Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coffeescript / Jquery binding events best practice [closed]

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?

like image 995
Ladislav Zigo Avatar asked Aug 14 '13 18:08

Ladislav Zigo


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).

Should you use CoffeeScript?

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.


2 Answers

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.

like image 119
arghbleargh Avatar answered Sep 30 '22 07:09

arghbleargh


CoffeeScript introduced an entire piece of syntax specifically for this problem: The fat arrow, =>. Use it:

$('#id4').click (event) =>
  @id4clicks++
  alert @id4clicks
like image 34
meagar Avatar answered Sep 30 '22 08:09

meagar