Rambling Labs Blog Ramblings on software development

  • CoffeeScript: The '=>' operator

    As you may know, I've been playing around with CoffeeScript for a couple of months now.

    One of CoffeeScript's jewels that I haven't talked about yet and that I've been using lately on the jQuery Rambling Slider codebase, is the => operator. It is basically a custom function definition, which binds that function to the current context. That is, it ties the this value of the outer scope to the this value of the function being defined.

    How many times, writing JavaScript, have you done something like this:

    var outerFunctionWithCallback = function(options, callback) {
      /* Do something with options */
      callback();
    };
    
    var theFunction = function(){
      var self = this;
      this.doFirstThing = function() { /* ... */ };
    
      this.doSecondThing = function() { /* ... */ };
    
      var initialize = function() {
        self.doFirstThing();
        self.doSecondThing();
      };
    
      outerFunctionWithCallback({/* options */}, initialize);
    };
    

    Or it's CoffeeScript equivalent:

    outerFunctionWithCallback = (options, callback) ->
      # Do something with options
      callback()
    
    theFunction = ->
      self = @
      @doFirstThing = -> # ...
    
      @doSecondThing = -> # ...
    
      initialize = ->
        self.doFirstThing();
        self.doSecondThing();
    
      outerFunctionWithCallback {}, initialize
    

    Notice the definition of a variable named self, just for the sake of being able to access the outer function context (theFunction) from an inner function (initialize).

    Well, with CoffeeScript's => operator, you won't have to do this anymore!
    Of course, as long as you're not expecting another value for this, as is the case for jQuery plugins and functions bound to events.

    So, you can turn the code above into this:

    outerFunctionWithCallback = (options, callback) ->
      # Do something with options
      callback()
    
    theFunction = ->
      @doFirstThing = -> # ...
    
      @doSecondThing = -> # ...
    
      initialize = =>
        @doFirstThing();
        @doSecondThing();
    
      outerFunctionWithCallback {}, initialize;
    

    No need to write self anymore :).
    Beautiful, right?

    Enjoy!

  • blog comments powered by Disqus