Share
Embed
CoffeeScript, le javascript simple et élégant
Présentation effectuée à Paris Web le 15 octobre 2011.
jblanche
October 15, 2011
Transcript
87 slides
-
1995 Mais aussi : Création de LiveScript, qui deviendra JavaScript
par Brendan Eich -
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"> :( -
1998 Profusion de scripts, personne ne comprend le JavaScript, mais
tout le monde veut ajouter du dynamisme aux pages web ! -
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."); }; -
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 ... -
2005 / 2006 Frameworks JS : Prototype.JS / jQuery $$("a.pulsate").each(Effect.Pulsate);
$("div.test") .add("p.quote") .addClass("blue") .slideDown("slow"); -
2005 / 2006 Gros travail de standardisation. On écrit une
fois, les frameworks se chargent de la compatibilité cross-navigateurs. -
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/'); -
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. -
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 -
Mais Foo.method = function() { var that = this; function
test() { // Use that instead of this here } test(); } -
Mais 0 == "" // true 0 == "0" //
true false == "0" // true null == undefined // true " \t\r\n" == 0 // true ... -
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. -
- « 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. -
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) -
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]); } } -
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]); } } -
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]) } } -
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]) -
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) -
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 -
//Des itérateurs bien foutus names = ['Eich', 'Crockford', 'Ashkenas'] longNames
= [] for name in names longNames.push name if name.length > 5 La transition -
//Des comprehensions names = ['Eich', 'Crockford', 'Ashkenas'] longNames = (name
for name in names when name.length > 5 ) La transition -
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 ) -
La transition // JS Natif var request = function ()
{ $.get(this.person.url, (function(data) { $(this.el).html(data); }).bind(this); ); }; -
La transition // var request = function () { $.get(this.person.url,
(function(data) { $(this.el).html(data); }).bind(this); ); }; -
La transition // Point virgules request = function () {
$.get(this.person.url, (function(data) { $(this.el).html(data) }).bind(this) ) } -
La transition // Accolades request = function () $.get(this.person.url, (function(data)
$(this.el).html(data) ).bind(this) ) -
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 ) -
La transition // this ! request = function () $.get(@person.url,
(function(data) $(@el).html data ).bind @ ) -
La transition // functions ! request = -> $.get(@person.url, ((data)->
$(@el).html data ).bind @ ) -
La transition // Binding ! request = -> $.get(@person.url, (data)=>
$(@el).html data ) -
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 ) -
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}..." -
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 } }; -
if else then ... // JavaScript date = friday ?
sue : jill; # CoffeeScript date = if friday then sue else jill -
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 -
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 -
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 -
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 -
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 ] -
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); } -
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 -
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] -
Existential Operator # CoffeeScript fun = true if coffeescript? and
not dart? day ?= 'saterday' zip = lottery.drawWinner?().address?.zipcode -
Binding // JavaScript $('.shopping_cart').bind('click', $.proxy(function(event) { this.customer.purchase(this.cart); }, this)); #
CoffeeScript $('.shopping_cart').bind 'click', (event) => @customer.purchase @cart -
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> -
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'] -
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); -
En CoffeeScript Shape = (x, y) -> @x = x
@y = y Shape.prototype.center = -> [ @x, @y ] Shape.prototype.area = -> 0 point = new Shape 13, 37 -
Mieux Shape = (@x, @y) -> Shape::centre = -> [
@x, @y ] Shape::area = -> 0 point = new Shape 13, 37 -
Encore Mieux # CoffeeScript class Shape constructor: (@x, @y) ->
centre: -> [ @x, @y ] area: -> 0 point = new Shape 13, 37 -
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 -
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) -
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 -
Outils Des bundles pour vos éditeurs : Textmate, emacs, gedit,
vim, SublimeText2, Eclipse... https://github.com/jashkenas/coffee-script/wiki/ Text-editor-plugins -
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/ -
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 . -
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 ! -
En ligne The Little Book on CoffeeScript http://arcturo.github.com/library/coffeescript/ index.html et
Smooth CoffeeScript http://autotelicum.github.com/Smooth- CoffeeScript/ -
Papier CoffeeScript : Accelerated JavaScript Development Premier livre complet sur
CoffeeScript, préfacé par Jérémy Ashkenas.