Skip to content

Commit b58b6b8

Browse files
committed
Merge pull request coffeescript-cookbook#5 from sebslomski/master
jQuery callback bindings.
2 parents c474be9 + 9a1fc96 commit b58b6b8

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
---
2+
layout: recipe
3+
title: Callback bindings # using => instead of ->
4+
chapter: jQuery
5+
---
6+
7+
h2. Problem
8+
9+
You want to bind a callback function to an object.
10+
11+
h2. Solution
12+
13+
{% highlight coffeescript %}
14+
$ ->
15+
class Basket
16+
constructor: () ->
17+
@products = []
18+
19+
$('.product').click (event) =>
20+
@add $(event.target).attr 'id'
21+
22+
add: (product) ->
23+
@products.push product
24+
console.log @products
25+
26+
new Basket()
27+
{% endhighlight %}
28+
29+
h2. Discussion
30+
31+
By using the fat arrow => instead of the normal arrow -> the function gets
32+
automatically bound to the object and can access the @-variable

0 commit comments

Comments
 (0)