Thin and Fat Arrows in CoffeeScript February 13, 2012

The difference between -> and => is often overlooked due to the ease of always using =>. We can grasp the difference by this example which should trigger a console.log() when an element is clicked and double-clicked.

 1  this.callback = ->
 2    console.log 'Callback triggered!'
 3  $('#id').bind 'click', -> @callback()
 4  $('#id').bind 'dbclick', => @callback()
 1  var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
 2  this.callback = function() {
 3    return console.log('Callback triggered!');
 4  };
 5  $('#id').bind('click', function() {
 6    // this is bound to the HTML element, which has no callback() function.
 7    return this.callback();
 8  });
 9  $('#id').bind('dbclick', __bind(function() {
10    // this is bound to the local context by __bind(), which does have a callback() function.
11    return this.callback();
12  }, this));

If we were to click on the bound element, it would cause a JavaScript error since there is no callback() function in this context. jQuery’s bind() function assigns the HTML element as the context.

Dissimilarly, if we were to double-click on the bound element it would trigger the callback() function. The __bind() function defined on line 1 uses apply to assign the correct context. The same behavior can be replicated by using jQuery.proxy as follows.

 1  this.callback = ->
 2    console.log 'Callback triggered!'
 3  $('#id').bind 'click', -> @callback()
 4  $('#id').bind 'dbclick', jQuery.proxy(->
 5    @callback()
 6  , @)
 1  this.callback = function() {
 2    return console.log('Callback triggered!');
 3  };
 4  $('#id').bind('click', function() {
 5    // this is bound to the HTML element, which has no callback() function.
 6    return this.callback();
 7  });
 8  $('#id').bind('dbclick', jQuery.proxy(function() {
 9    // this is bound to the local context by jQuery.proxy(), which does have a callback() function.
10    return this.callback();
11  }, this));
blog comments powered by Disqus