0

When I'm writing coffee script I tend to do this an awful lot (pseudo code):

$link.click (e) =>
  this._clicked(e)

Is there really not some way to bind transparently in CoffeeScript? I'd like to be able to do:

$link.click =this._clicked

or something, which would bind my this._clicked method, directly to the event, keeping its this pointer

any ideas?

update

_clicked would be defined as:

_clicked: (e) ->
  # some code
hippietrail
  • 15,848
  • 18
  • 99
  • 158
Michael Baldry
  • 1,990
  • 2
  • 14
  • 28

1 Answers1

2

Nothing special with coffeescript. Just do

$link.click @_clicked

And then define _clicked as

_clicked: (e) =>
  # some code

It'll pass this._clicked as the handler for the click event of link.

You can pass any function as callbacks like this. The keypoint is to not execute the function (there are no () in @_clicked). A function in JS is a normal variable, which can be passed around as parameters to other functions.

With

$link.click ->

youre just passing a function to .click directly without storing it into a variable.

To keep the this you either define @_clicked with a fat arrow or you use JavaScripts bind function which returns a function where this is bound to a certain value.

CoffeeScript is not adding any extra functionality to JavaScript. The Fat arrow just does a bind similar to the bind function from the link (if its used in a method definition of a class) or just does the var _this = this trick when a function is defined inside a function.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
ohcibi
  • 2,518
  • 3
  • 24
  • 47
  • This isn't what I mean, though its a good point you can use @_clicked for functions, instead of this. I've just always seen it as a instance variable kind of thing (I know functions are, but it just feels different, coming from ruby) – Michael Baldry Mar 26 '13 at 12:56