CoffeeScript : Avoid using jQuery proxy and .bind(this)

20 Oct 2013

There are many times I need to execute the methods, which are triggered by an event handler/callbacks to execute without changing the context. It helps me to use instance variables or methods inside callback. I usually use $.proxy or .bind() method to achieve this.

When I was learning CoffeeSctipt, I continued using the same. But later I came to know CoffeeScript have much handy way to do the same.

In CS, you can use Fat arrow functions for this.

class Form
  constructor: (root) ->
    @root = root;
    @root.on 'submit', @onSubmit
    @root.on 'submit', @onSub

  onSub:(e) ->
    console.log(this)
    return false;
  
  onSubmit:(e) =>
    console.log(this)
    return false;

In the above code, I want to execute the onSubmit method in the context of Form. Since the onSubmit is trigger by the submit event, by default its context will be element which the event is binded.

I hope I am able to convince you the differece between thin arrow and fat arrow function. You can get the detailed description on the CoffeeScript doc.

Also you can look into the code generated by CoffeeScript when you use fat arrow.

In ECMAScript 5

If you are using ECMAScript 5, As I saild before you can use .bind() method.

var Form = (function(){
  function Form(root){
    this.root = root;
    this.root.on('submit', this.onSubmit.bind(this));
    this.root.on('submit', this.onSub);
  }

  Form.prototype.onsubmit = function(e){
    console.log(this)
    return false;
  }

  Form.prototype.onSub = function(e){
    console.log(this)
    return false;
  }

  return Form;
})()
If you particularly enjoy my work, I appreciate donations given with Gittip.
comments powered by Disqus