Samstag, 8. Dezember 2012

From JavaScript to CoffeeScript

CoffeeScript makes you write clean and more readable JavaScript code. Syntactic sugar! Typically you'll code 30% less lines. Good to know the code compiles one-to-one into the equivalent JavaScript, and there is no interpretation at runtime. As a first example I convert the snippet of the cyclic remote link using jQuery into CoffeeScript. You can compare the simple logic in JavaScript and CoffeeScript yourself. First the code in JavaScript once again:
    jQuery.each($('a.auto_remote'), function(){
     setInterval(function(remote_link) {
        $.ajax({ url: $(remote_link).attr('href') });
      }, 10000, this);
In CoffeeScript it is tidy like this:
$(document).ready ->
  jQuery.each $("a.auto_remote"), ->
    setInterval ((remote_link) ->
      $.ajax url: $(remote_link).attr("href")
    ), 10000, this
The first that attracts attention is the syntactic sugar like Ruby, Python or Haskell also offer. No semicolons, less brackets, just more readable. Furthermore you noticed the alias "->" for functions. Practical:
    // some codes
In CoffeeScript:
$(document).ready -> // some codes
... sweet.
Read the CoffeeScript Tutorial and check how your JavaScript looks like converted into CoffeeScript.
Supported by CoffeeScript 1.4.0

Keine Kommentare:

Kommentar veröffentlichen