From 9a1fc96805bdcadafe7a0140b30b2dd4336c8a9d Mon Sep 17 00:00:00 2001 From: Sebastian Slomski Date: Thu, 12 May 2011 14:47:03 +0200 Subject: [PATCH] jquery callback bindings --- .../jquery/callback-bindings-jquery.textile | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 chapters/jquery/callback-bindings-jquery.textile diff --git a/chapters/jquery/callback-bindings-jquery.textile b/chapters/jquery/callback-bindings-jquery.textile new file mode 100644 index 0000000..c656dc3 --- /dev/null +++ b/chapters/jquery/callback-bindings-jquery.textile @@ -0,0 +1,32 @@ +--- +layout: recipe +title: Callback bindings # using => instead of -> +chapter: jQuery +--- + +h2. Problem + +You want to bind a callback function to an object. + +h2. Solution + +{% highlight coffeescript %} +$ -> + class Basket + constructor: () -> + @products = [] + + $('.product').click (event) => + @add $(event.target).attr 'id' + + add: (product) -> + @products.push product + console.log @products + + new Basket() +{% endhighlight %} + +h2. Discussion + +By using the fat arrow => instead of the normal arrow -> the function gets +automatically bound to the object and can access the @-variable