Upgrade to Pro — share decks privately, control downloads, hide ads and more …

CoffeeScript, le javascript simple et élégant

jblanche
October 15, 2011

CoffeeScript, le javascript simple et élégant

Présentation effectuée à Paris Web le 15 octobre 2011.

jblanche

October 15, 2011
Tweet

Other Decks in Programming

Transcript

  1. 1998 Mais aussi : <img style="Z-INDEX: 108; POSITION: absolute; TOP:

    127px; LEFT: 8px" id="Image1" onMouseOver="MM_swapImage('Image1','','images/b1_over.jpg',1)" onMouseOut="MM_swapImgRestore()" border="0" name="Image1" alt="home" src="images/b1.jpg" width="170" height="20"> :(
  2. 1998 Profusion de scripts, personne ne comprend le JavaScript, mais

    tout le monde veut ajouter du dynamisme aux pages web !
  3. 1999 / 2004 if (typeof XMLHttpRequest == "undefined") XMLHttpRequest =

    function () { try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e) {} try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e) {} try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {} //Microsoft.XMLHTTP points to Msxml2.XMLHTTP and is redundant throw new Error("This browser does not support XMLHttpRequest."); }; if (typeof XMLHttpRequest == "undefined") XMLHttpRequest = function () { try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e) {} try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e) {} try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {} //Microsoft.XMLHTTP points to Msxml2.XMLHTTP and is redundant throw new Error("This browser does not support XMLHttpRequest."); };
  4. 1999 / 2004 Ajax ! (depuis devenu AJAJ ) Dès

    1999 dans IE5 En 2002 Dans Gecko 1.0 (Firefox 0.1 ! ) Safari 1.2 en 2004 ...
  5. 2005 / 2006 Frameworks JS : Prototype.JS / jQuery $$("a.pulsate").each(Effect.Pulsate);

    $("div.test") .add("p.quote") .addClass("blue") .slideDown("slow");
  6. 2005 / 2006 Gros travail de standardisation. On écrit une

    fois, les frameworks se chargent de la compatibilité cross-navigateurs.
  7. 2010 Le retour vers le futur serveur : Node.JS... var

    http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain' }); res.end('Hello World\n'); }).listen(1337, "127.0.0.1"); console.log('Server running at http://127.0.0.1:1337/');
  8. 2010 JavaScript est partout ! 0 développeur JavaScript au chômage

    ! Les outils se multiplient, se professionnalisent... c.f. : JavaScript as a Programming Language par Marco Cedaro.
  9. Mais JavaScript a gardé ses défauts ! 2.toString(); // raises

    SyntaxError for(var i = 0; i < 10; i++) { setTimeout(function() { console.log(i); }, 1000); } // 10 10 10 10 10 10 10 10 10 10
  10. Mais Foo.method = function() { var that = this; function

    test() { // Use that instead of this here } test(); }
  11. Mais 0 == "" // true 0 == "0" //

    true false == "0" // true null == undefined // true " \t\r\n" == 0 // true ...
  12. CoffeeScript is a little language that compiles into JavaScript. Underneath

    all of those embarrassing braces and semicolons, JavaScript has always had a gorgeous object model at its heart. CoffeeScript is an attempt to expose the good parts of JavaScript in a simple way.
  13. - « Ce n’est que du JavaScript » - Possibilité

    d’utiliser n’importe qu’elle librairie JavaScript avec CoffeeScript. - La version compilée est lisible et correctement indentée. - Elle passe JSLint, fonctionne sur toute les implémentation de JS et est aussi ou plus rapide que du JS écrit à la main.
  14. A quoi ça ressemble ? number = 42 number =

    -42 if opposite square = (x) -> x * x math = root: Math.sqrt square: square alert "I knew it!" if elvis? cubes = (math.cube num for num in list)
  15. La transition // JS Natif var names = ['Eich', 'Crockford',

    'Ashkenas']; var longNames = [] ; for (i = 0, length = names.length; i < length ; i++) { if(names[i].length > 5){ longNames.push(names[i]); } }
  16. La transition // Plus de var names = ['Eich', 'Crockford',

    'Ashkenas']; longNames = [] ; for (i = 0, length = names.length; i < length ; i++) { if(names[i].length > 5){ longNames.push(names[i]); } }
  17. La transition // Plus de point virgule names = ['Eich',

    'Crockford', 'Ashkenas'] longNames = [] for (i = 0, length = names.length; i < length ; i++) { if(names[i].length > 5){ longNames.push(names[i]) } }
  18. La transition // plus d’accolades names = ['Eich', 'Crockford', 'Ashkenas']

    longNames = [] for (i = 0, length = names.length; i < length ; i++) if(names[i].length > 5) longNames.push(names[i])
  19. La transition //Une syntaxe de if / else plus sympa

    names = ['Eich', 'Crockford', 'Ashkenas'] longNames = [] for (i = 0, length = names.length; i < length ; i++) longNames.push(names[i]) if (names[i].length > 5)
  20. La transition // Trop de parenthèses names = ['Eich', 'Crockford',

    'Ashkenas'] longNames = [] for (i = 0, length = names.length; i < length ; i++) longNames.push names[i] if names[i].length > 5
  21. //Des itérateurs bien foutus names = ['Eich', 'Crockford', 'Ashkenas'] longNames

    = [] for name in names longNames.push name if name.length > 5 La transition
  22. //Des comprehensions names = ['Eich', 'Crockford', 'Ashkenas'] longNames = (name

    for name in names when name.length > 5 ) La transition
  23. Rappel // JavaScript var names = ['Eich', 'Crockford', 'Ashkenas']; var

    longNames = [] ; for (i = 0, length = names.length; i < length ; i++) { if(names[i].length > 5){ longNames.push(names[i]); } } # CoffeeScript names = ['Eich', 'Crockford', 'Ashkenas'] longNames = (name for name in names when name.length > 5 )
  24. La transition // JS Natif var request = function ()

    { $.get(this.person.url, (function(data) { $(this.el).html(data); }).bind(this); ); };
  25. La transition // var request = function () { $.get(this.person.url,

    (function(data) { $(this.el).html(data); }).bind(this); ); };
  26. La transition // Point virgules request = function () {

    $.get(this.person.url, (function(data) { $(this.el).html(data) }).bind(this) ) }
  27. La transition function request () { $.get(this.person.url, (function(data) { $(this.el).html(data);

    }).bind(this) ) } // parenthèses request = function () $.get(this.person.url, (function(data) $(this.el).html data ).bind this )
  28. La transition // this ! request = function () $.get(@person.url,

    (function(data) $(@el).html data ).bind @ )
  29. Rappel // JS Natif var request = function () {

    $.get(this.person.url, (function(data) { $(this.el).html(data); }).bind(this); ); }; # Coffee request = -> $.get(@person.url, (data) => $(@el).html data )
  30. Arguments par défaut // JavaScript var fill = function(container, liquid)

    { if (liquid == null) liquid = "coffee"; return "Filling the " + container + " with " + liquid + "..."; }; # CoffeeScript fill = (container, liquid = "coffee") -> "Filling the #{container} with #{liquid}..."
  31. Syntaxe des objets # CoffeeScript kids = brother: name: "Max"

    age: 11 sister: name: "Ida" age: 9 // JavaScript kids = { brother: { name: "Max", age: 11 }, sister: { name: "Ida", age: 9 } };
  32. if else then ... // JavaScript date = friday ?

    sue : jill; # CoffeeScript date = if friday then sue else jill
  33. Splats # CoffeeScript gold = silver = rest = "unknown"

    awardMedals = (first, second, others...) -> gold = first silver = second rest = others contenders = [ "Michael Phelps" "Liu Xiang" "Yao Ming" "Allyson Felix" "Shawn Johnson" ] awardMedals contenders... console.log "Gold: " + gold # Gold: Michael Phelps console.log "Silver: " + silver # Silver: Liu Xiang console.log "The Field: " + rest # The Field: Yao Ming,Allyson Felix,Shawn Johnson
  34. Itération sur les propriétes d’un objet # CoffeeScript coworkers =

    bea: 10 juliette: 9 erik: 12 cyril: 8 for firstname, age of coworkers console.log "#{firstname} a #{age} ans" // bea a 10 ans // juliette a 9 ans // erik a 12 ans // cyril a 8 ans
  35. Itération sur les propriétes d’un objet # CoffeeScript Object::foo =

    'bar' user = age: 26 firstname: 'Jonathan' lastname: 'Blanchet' twitter: '@jblanchefr' for key, value of user console.log "#{key} is #{value}" # age is 26 # firstname is Jonathan # lastname is Blanchet # twitter is @jblanchefr # foo is bar
  36. Itération sur les propriétes d’un objet # CoffeeScript Object::foo =

    'bar' user = age: 26 firstname: 'Jonathan' lastname: 'Blanchet' twitter: '@jblanchefr' for own key, value of user console.log "#{key} is #{value}" # age is 26 # firstname is Jonathan # lastname is Blanchet # twitter is @jblanchefr
  37. Array # CoffeeScript numbers = [0, 1, 2, 3, 4,

    5, 6, 7, 8, 9] copy = numbers[0...numbers.length] # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] middle = copy[3..6] # [3, 4, 5, 6] numbers[3..6] = [-3, -4, -5, -6] # [0, 1, 2, -3, -4, -5, -6, 7, 8, 9] numbers[7..] # [ 7, 8, 9 ] numbers[..4] # [ 0, 1, 2, -3, -4 ] numbers[7..-2] # [ 7, 8 ] numbers[-3..-1] # [ 7, 8, 9 ]
  38. Do # CoffeeScript for i in [0...10] do (i) ->

    setTimeout (-> console.log i), 1000 // JavaScript for(var i = 0; i < 10; i++) { (function(e) { setTimeout(function() { console.log(e); }, 1000); })(i); }
  39. Tout est expression # CoffeeScript hasFuture = switch language when

    'Ruby', 'JavaScript', 'Coffeescript' then true when 'Cobol', 'PHP', 'Dart' then false else 'maybe' eldest = if john.age > flavie.age then john else flavie
  40. Les opérateurs sympas # CoffeeScript launch() if ignition is on

    volume = 10 if band isnt SpinalTap letTheWildRumpusBegin() unless answer is no if car.speed < limit then accelerate() winner = yes if pick in [47, 92, 13]
  41. Existential Operator # CoffeeScript fun = true if coffeescript? and

    not dart? day ?= 'saterday' zip = lottery.drawWinner?().address?.zipcode
  42. String interpolation # CoffeeScript conference = "ParisWeb" quote = "You're

    attending #{conference} " sentence = "Avec le don d'ubiquité, vous auriez pu assister à #{18 + 17 + 24} conférences/ateliers ces trois dernier jours !" author = 'Joshua Bloch' quote = """<blockquote> The cleaner and nicer the program, the faster it's going to run. And if it doesn't, it'll be easy to make it fast. </blockquote> <cite>#{author}</cite> """ # <blockquote> # The cleaner and nicer the program, # the faster it's going to run. # And if it doesn't, it'll be easy to make it fast. # </blockquote> # <cite>Joshua Bloch</cite>
  43. Des Regex cool # CoffeeScript pattern = /// ^\(?(\d{3})\)? #

    Capture area code, ignore optional parens [-\s]?(\d{3}) # Capture prefix, ignore optional dash or space -?(\d{4}) # Capture line-number, ignore optional dash /// [area_code, prefix, line] = "(555)123-4567".match(pattern)[1..3] # => ['555', '123', '4567']
  44. Le JS orienté objet // JavaScript var Shape = function(x,

    y) { this.x = x; this.y = y; }; Shape.prototype.center = function() { return [ this.x, this.y ]; }; Shape.prototype.area = function() { return 0; }; var point = new Shape(13, 37);
  45. En CoffeeScript Shape = (x, y) -> @x = x

    @y = y Shape.prototype.center = -> [ @x, @y ] Shape.prototype.area = -> 0 point = new Shape 13, 37
  46. Mieux Shape = (@x, @y) -> Shape::centre = -> [

    @x, @y ] Shape::area = -> 0 point = new Shape 13, 37
  47. Encore Mieux # CoffeeScript class Shape constructor: (@x, @y) ->

    centre: -> [ @x, @y ] area: -> 0 point = new Shape 13, 37
  48. Héritage # CoffeeScript class Shape constructor: (@x, @y) -> centre:

    -> [ @x, @y ] area: -> 0 class Circle extends Shape constructor: (x, y, @radius) -> super x, y area: -> Math.PI * @radius * @radius circle = new Circle(10, 10, 1) console.log circle.area() # 3.141592653589793
  49. Installation Il vous faudra Node.JS Mac : Homebrew + brew

    install node Linux : Compilation ou package de la distribution. Windows : Build pré-compilés (http://nodejs.org/ dist/v0.5.7/node.exe)
  50. Installation Puis npm Linux, Mac : Windows : C’est le

    bordel mais curl http://npmjs.org/install.sh | sh http://npmjs.org/doc/README.html#Installing-on-Windows-Experimental
  51. Outils Des bundles pour vos éditeurs : Textmate, emacs, gedit,

    vim, SublimeText2, Eclipse... https://github.com/jashkenas/coffee-script/wiki/ Text-editor-plugins
  52. La doc Jeremy Ashkenas a également écrit un outil de

    génération de doc, Docco qui mérite le coup d’oeil ! http://jashkenas.github.com/docco/
  53. Le débug Cela évoluera (des bugs sont ouverts) mais pour

    l’instant, les outils de débug des navigateurs ne savent pas interpréter le CoffeeScript. Du coup les outils vous donnent les numéros de ligne dans le JS et c’est à vous de retrouver la correspondance dans le CoffeeScript .
  54. Le débug De plus, il y a une impossibilité dans

    CoffeeScript, nommer les fonctions de callback. Du coup le débug peut être un peu moins clair dans la stack trace. Mais franchement, la balance penche clairement du côté des avantages et non des inconvénients !
  55. En ligne The Little Book on CoffeeScript http://arcturo.github.com/library/coffeescript/ index.html et

    Smooth CoffeeScript http://autotelicum.github.com/Smooth- CoffeeScript/