SlideShare uma empresa Scribd logo
1 de 58
JavaScript per a
desenvolupadors de C#
      Edin Kapić
JavaScript
                != C#
   Edin Kapić
Qui sóc?

                        @ekapic
Edin Kapić
Key Consultant (SharePoint)
ekapic@pasiona.com


                                  SUG.CAT
                                  SharePoint User Group
                                  Catalunya
JavaScript: “With or Without You”




                        Brendan Eich
                        “El pare de la
                           criatura”
Com hem arribat fins aquí?



        1995                     1996              1997
Netscape Navigator 2.0   Internet Explorer 3.0   ECMAScript
  Mocha/LiveScript              JScript
1999                 2005             2006
XMLHttpRequest   Jesse James Garrett   John Resig
(OWA Exchange            AJAX            jQuery
    2000)
TypeScript


  2009      2010       2011           2012
PhoneGap   Node.js   Windows 8   SharePoint 2013
                                   TypeScript
Hem de donar el salt
Firebug / IE Dev Tools


                          JSLint



               JsFiddle
                          Firebug
Les eines                 Lite
JavaScript és bo ...
• Llenguatge dinàmic
• Notació literal potent
• “Loose-typed”

• “JS is Lisp in C Clothing” (Douglas
  Crockford)
                                        http://bit.ly/Qn0qLi
... però té coses dolentes
•   Variables globals implícites
•   Variable hoisting
                             '' == '0'              //   false
•   Function hoisting        0 == ''
                             0 == '0'
                                                    //
                                                    //
                                                         true
                                                         true
                             false == 'false'       //   false
•   Prototype Leaking        false == '0'
                             false == undefined
                                                    //
                                                    //
                                                         true
                                                         false

•
                             false == null          //   false
    ==                       null == undefined      //   true
                                  ' trn ' == 0   //   true
JavaScript != C#
• C#                   • JavaScript
  – Talla pa             – Talla pa
  – Té mecanismes de     – Et pots fer mal
    seguretat            – Es un tros de metall
  – És complex             amb un mànec
Bo en C#, dolent en JS
• La sintaxi semblant ens pot portar a fer
  coses que a C# són bones pràctiques
• Però poden tenir conseqüències greus a
  JS

• “If it walks like a duck...”
JS != C# 1: Tipus de dades
Simples       Complexos
• Number      • Object
• String      • Array
• Boolean     • Function
• Undefined   • RegEx
• Null        • Date
JS != C# 2: Variables globals
  • Tota variable no assignada a un
    objecte, s’assigna a window

  • var a = 1;
  • window.a = 1;

                            http://jsfiddle.net/wQDwN/
JS != C# 3: “Variable
 Hoisting”
• Només dos nivells: global i funció
  – { } no crea àmbit de variable (com a
    C#)
• La variable declarada puja fins el
  principi de la funció dins la qual està
  declarada
  – /*.....*/ var a = 1;
                                  http://jsfiddle.net/NE2Km/3/
Recomanació
 • Ser conscient dels tipus de dades
 • No contaminar window
 • Declarar variables a dalt de tot (fer el
   hoisting explícit)
JS != C# 4: Wrappers
• JS estil C#
  var myVar = new Object();
  var myArr = new Array();


• JS estil pur
  var myVar = {};
  var myArr = [];
Recomanació
• No fer servir wrappers innecessàriament
• Aprendre la notació literal d’objectes de JS
JS != C# 5: Truthy / Falsey
Valors que donen true   Valors que donen false

•   "0"                 •   false
•   "false"             •   0
                        •   ""
•   Objectes buits
                        •   null
•   Tota la resta
                        •   undefined
                        •   NaN
Recomanació
• Simplifiquem els condicionals
  if(myVar != "" || myVar != undefined)
  if(myVar)
• Inicialitzem els valors per defecte
  if(myVar == "") { myVar = "Hola"; }
  myVar = myVar || "hola";
JS != C# 6: L’operador ==
• Comparació
  if(false == 0)      // true
  if(false === 0)     // false


• L’operador == intenta convertir els valors i
  gairebé segur que no és el que volem
Comparació “indeterminista”
(false == 0);               //   true
(false == "");              //   true
(0 == "");                  //   true
(null == false);            //   false
(null == null);             //   true
(undefined == undefined);   //   true
(undefined == null);        //   true
(NaN == null);              //   false
(NaN == NaN);               //   false
Recomanació
• Fem servir els operadors === i !== per
  defecte
• No fan conversió de valors
• Es comporten com els operadors
  “habituals” == i != de C#
JS != C# 7: Altres “perles”
•   parseInt()
•   L’operador + http://jsfiddle.net/tbMX2/
•   NaN http://jsfiddle.net/vVgB9/
•   “Prototype Leak”
Funcions
Funcions de JavaScript
• Són objectes, per tant s’hi
  poden afegir propietats
• Es poden passar com a
  paràmetres a altres funcions
• Hi ha dues maneres de
  declarar funcions
Manera 1: Declaracions
• La declaració de la funció es fa així
  function foo() { /* .... */ }


• La funció declarada fa “hoisting” i és
  disponible a tot el codi JS,
  independentment de l’ordre
                                 http://jsfiddle.net/TQ6LG/
Manera 2: Expressions
• També podem assignar la funció a una
  variable mitjançant una expressió:
   var foo = function () { /* ... */ };


• En aquest cas no hi ha “hoisting”
• Podem pensar que una declaració és
  realment una expressió posada a dalt de
  tot                               http://jsfiddle.net/NrQhM/
Equivalències
•   function foo() { /* .... */ }
•   var foo = function () { /* ... */ };
•   var foo = function foo () { /* ... */ };
•   var foo = function bar () { /* ... */ };

• Les dues últimes es fan servir per a funcions
  recursives
• Les expressions fan explícita la declaració
Codi d’un sol ús
• Podem assignar una funció anònimament i
  no recollir-la
• Útil per a executar un codi privat i d’una
  sola vegada

• (function () { /* ... */ })();
                               http://jsfiddle.net/YAe9S/1/
Anidament de funcions
• Les funcions són objectes i poden contenir
  altres funcions
var foo = function() {
    function bar() {
       /* ... */
    }
    return bar();
};
foo();                          http://jsfiddle.net/XUswD/
Tancaments (Closures)
• El tancament és una manera d’associar la
  funció amb els seus paràmetres d’entrada
   – És el manteniment de les variables locals
     desprès de que la funció hagi retornat
var bind = function(x) {
    return function(y) { return x + y; };
}
var plus5 = bind(5);
alert(plus5(3));                     http://jsfiddle.net/xWAm4/
Recomanacions
• Dedicar temps per a jugar amb les
  funcions en JS és imprescindible
  – Hi ha molts exemples que es poden provar
    amb JsFiddle
• Comprendre els tancaments és important
  per a entendre els event handlers i
  encapsulament
JavaScript al segle XXI
Anem tirant?
O estem al dia?
Regla #1: Unobtrusive
JavaScript
• El codi JS s’ha d’afegir sense impactar el
  HTML de la pàgina
  <input type="text" name="date“
  onchange="validateDate()" />

  window.onload = function() {
      document.getElementById('date').onchange
  = validateDate;
  };
Regla #2: Modularitat
• El nostre codi JS no pot
  col·lisionar amb qualsevol
  altre codi JS present
• Encapsulem el nostre codi
  en namespaces
• Fem servir try/catch
Mètodes d’encapsulament
• Cap (objecte window)
• Tot privat (funció anònima auto-executada)

• Tot públic (objecte literal)
• Barreja public/privat (Revealing Module)
Objecte literal
var car = {
    status: "off",
    start: function() {
        this.status = "on";
    },
    getStatus: function() {
        return "the car is " + this.status;
    }
};
car.start();
alert(car.getStatus());         http://jsfiddle.net/DY2Zw/
Revealing Module
var car = (function() {
    var pubCar = {}, var innerStatus = "off";
    pubCar.start = function() { innerStatus = "on"; }
    pubCar.status = function() {
        return "the car is “ + innerStatus; }
    return pubCar;
}());
car.start();
alert(car.status());                http://jsfiddle.net/AUzNT/
Recomanacions
• Fer servir Revealing Module per a tenir
  encapsulament totalment controlat per
  nosaltres
• Aïllar-nos d’altres llibreries
  http://jsfiddle.net/uKuLw/
• Fer servir objecte literal per a fer objectes
  senzills (p.ex. DTOs)
  – La sintaxi és diferent
Regla #3: Abstracció
 • Cal abstreure’s dels detalls del navegador
                                       concret
                        • Existeixen
                          llibreries que ens
                          unifiquen les
                          diferències:
                          jQuery, AmplifyJS,
Llibreries que cal conèixer
•   MVVM: KnockoutJS
•   Plantilles: JsRender
•   Notificacions: SignalR, Toastr
•   Tests unitaris: QUnitJS
•   BDD: Jasmine
•   IoC/DI: Inject, RequireJS
KnockoutJS
 • Possibilita al patró MVVM
   (Model-View-ViewModel)
• Automatitza el binding
  bidireccional entre el viewmodel
  (JS) i la vista (HTML)
  http://knockoutjs.com/
  Demo: http://knockoutjs.com/examples/helloWorld.html
JsRender
• Permet fer “plantilles”
  d’elements HTML i
  enllaçar-les amb dades


    https://github.com/BorisMoore/jsrender
Demo: http://borismoore.github.com/jsrender/demos/step-by-step/05_for-tag.html
SignalR
• Notificacions asíncrones de
  servidor a client i vice-versa
• Útil per a notificacions de
  sistema a l’usuari
• http://signalr.net

• Demo: http://zooplet.com/tictactoe/
Toastr
   • Notificacions tipus “torrada”




   • https://github.com/CodeSeven/toastr
   • Demo: http://CodeSeven.github.com/toastr
QUnitJS                                   http://qunitjs.com/

• Proves unitàries per al
  codi de JavaScript
• Executable dins el
  navegador


Demo: http://jsfiddle.net/booyaa/kdEtk/
Jasmine
• Proves funcionals amb
  JavaScript
• Descriuen el resultat
  esperat i poden combinar-
  se per a formar casos d’ús

• https://github.com/pivotal/jasmine
•   Demo: http://pivotal.github.com/jasmine/
Inject / RequireJS
• Gestió de dependències entre
  components JS
• https://github.com/linkedin/inject
• Demo: http://bit.ly/wu2Pe1

• Alternativa: RequireJS
• http://requirejs.org
Microsoft TypeScript
• És un llenguatge basat en
  JavaScript
• Afegeix la comprovació en temps
  de compilació de referències,
  tipus, classes i interfícies
• (Trans)compila a JavaScript “pur”
• Disponible per a VS2012
• http://www.typescriptlang.org/
Resum
Recomanacions
• Invertir temps en aprendre els principis de
  JS i experimentar amb els exemples
• Repassar el codi existent amb JSLint
• Tenir en compte les llibreries de JS com a
  factor arquitectònic a les aplicacions
• JS està aquí per a quedar-s’hi
Bibliografia
• Douglas Crockford “JavaScript: The Good
  Parts” (O’Reilly)
• Addy Osmani “JavaScript Design
  Patterns” http://bit.ly/bMyoQ9
• http://jsbooks.revolunet.com/
JavaScript per a desenvolupadors de C#

Mais conteúdo relacionado

Mais de Edin Kapic

High-Trust Add-Ins SharePoint for On-Premises Development
High-Trust Add-Ins SharePoint for On-Premises DevelopmentHigh-Trust Add-Ins SharePoint for On-Premises Development
High-Trust Add-Ins SharePoint for On-Premises DevelopmentEdin Kapic
 
Extending Authentication and Authorization
Extending Authentication and AuthorizationExtending Authentication and Authorization
Extending Authentication and AuthorizationEdin Kapic
 
Rx la joya oculta de Net
Rx la joya oculta de NetRx la joya oculta de Net
Rx la joya oculta de NetEdin Kapic
 
ESPC15 - Extending Authentication and Authorization
ESPC15 - Extending Authentication and AuthorizationESPC15 - Extending Authentication and Authorization
ESPC15 - Extending Authentication and AuthorizationEdin Kapic
 
SPS London 2015 - IoT and Room Reservation Cloud-Style
SPS London 2015 - IoT and Room Reservation Cloud-StyleSPS London 2015 - IoT and Room Reservation Cloud-Style
SPS London 2015 - IoT and Room Reservation Cloud-StyleEdin Kapic
 
SPS Belgium 2015 - High-trust Apps for On-Premises Development
SPS Belgium 2015 -  High-trust Apps for On-Premises DevelopmentSPS Belgium 2015 -  High-trust Apps for On-Premises Development
SPS Belgium 2015 - High-trust Apps for On-Premises DevelopmentEdin Kapic
 
Personal Branding for Developers
Personal Branding for DevelopersPersonal Branding for Developers
Personal Branding for DevelopersEdin Kapic
 
SharePoint Saturday Stockholm 2015 - Building Maintainable and Testable Share...
SharePoint Saturday Stockholm 2015 - Building Maintainable and Testable Share...SharePoint Saturday Stockholm 2015 - Building Maintainable and Testable Share...
SharePoint Saturday Stockholm 2015 - Building Maintainable and Testable Share...Edin Kapic
 
ESPC14 Social Business Value Demystified
ESPC14 Social Business Value DemystifiedESPC14 Social Business Value Demystified
ESPC14 Social Business Value DemystifiedEdin Kapic
 
Maintainable Testable SharePoint Components SPSBE 2014
Maintainable Testable SharePoint Components SPSBE 2014Maintainable Testable SharePoint Components SPSBE 2014
Maintainable Testable SharePoint Components SPSBE 2014Edin Kapic
 
MVP Open Day 2014 - Hacking Human Behaviour
MVP Open Day 2014 - Hacking Human BehaviourMVP Open Day 2014 - Hacking Human Behaviour
MVP Open Day 2014 - Hacking Human BehaviourEdin Kapic
 
SPS Stockholm 7 Key Things for Building a Highly-Scalable SharePoint 2013 App
SPS Stockholm 7 Key Things for Building a Highly-Scalable SharePoint 2013 AppSPS Stockholm 7 Key Things for Building a Highly-Scalable SharePoint 2013 App
SPS Stockholm 7 Key Things for Building a Highly-Scalable SharePoint 2013 AppEdin Kapic
 
7 Key Things for Building a Highly-Scalable SharePoint 2013 App
7 Key Things for Building a Highly-Scalable SharePoint 2013 App7 Key Things for Building a Highly-Scalable SharePoint 2013 App
7 Key Things for Building a Highly-Scalable SharePoint 2013 AppEdin Kapic
 
Social Business Value Demystified: Real-World Experiences
Social Business Value Demystified: Real-World ExperiencesSocial Business Value Demystified: Real-World Experiences
Social Business Value Demystified: Real-World ExperiencesEdin Kapic
 
BcnDevCon13 - No Designer? No Problem!
BcnDevCon13 - No Designer? No Problem!BcnDevCon13 - No Designer? No Problem!
BcnDevCon13 - No Designer? No Problem!Edin Kapic
 
BcnDevCon12 - Una vuelta por Orchard CMS
BcnDevCon12 - Una vuelta por Orchard CMSBcnDevCon12 - Una vuelta por Orchard CMS
BcnDevCon12 - Una vuelta por Orchard CMSEdin Kapic
 
BcnDevCon12 - CQRS explicado a mi compañero arquitecto
BcnDevCon12 - CQRS explicado a mi compañero arquitectoBcnDevCon12 - CQRS explicado a mi compañero arquitecto
BcnDevCon12 - CQRS explicado a mi compañero arquitectoEdin Kapic
 
CatDotNet - Farmville para SharePoint
CatDotNet - Farmville para SharePointCatDotNet - Farmville para SharePoint
CatDotNet - Farmville para SharePointEdin Kapic
 
Universidad de La Habana - SharePoint, Listas y XSLT
Universidad de La Habana  - SharePoint, Listas y XSLTUniversidad de La Habana  - SharePoint, Listas y XSLT
Universidad de La Habana - SharePoint, Listas y XSLTEdin Kapic
 
SharePoint kao razvojna platforma za ASP.NET developere
SharePoint kao razvojna platforma za ASP.NET developereSharePoint kao razvojna platforma za ASP.NET developere
SharePoint kao razvojna platforma za ASP.NET developereEdin Kapic
 

Mais de Edin Kapic (20)

High-Trust Add-Ins SharePoint for On-Premises Development
High-Trust Add-Ins SharePoint for On-Premises DevelopmentHigh-Trust Add-Ins SharePoint for On-Premises Development
High-Trust Add-Ins SharePoint for On-Premises Development
 
Extending Authentication and Authorization
Extending Authentication and AuthorizationExtending Authentication and Authorization
Extending Authentication and Authorization
 
Rx la joya oculta de Net
Rx la joya oculta de NetRx la joya oculta de Net
Rx la joya oculta de Net
 
ESPC15 - Extending Authentication and Authorization
ESPC15 - Extending Authentication and AuthorizationESPC15 - Extending Authentication and Authorization
ESPC15 - Extending Authentication and Authorization
 
SPS London 2015 - IoT and Room Reservation Cloud-Style
SPS London 2015 - IoT and Room Reservation Cloud-StyleSPS London 2015 - IoT and Room Reservation Cloud-Style
SPS London 2015 - IoT and Room Reservation Cloud-Style
 
SPS Belgium 2015 - High-trust Apps for On-Premises Development
SPS Belgium 2015 -  High-trust Apps for On-Premises DevelopmentSPS Belgium 2015 -  High-trust Apps for On-Premises Development
SPS Belgium 2015 - High-trust Apps for On-Premises Development
 
Personal Branding for Developers
Personal Branding for DevelopersPersonal Branding for Developers
Personal Branding for Developers
 
SharePoint Saturday Stockholm 2015 - Building Maintainable and Testable Share...
SharePoint Saturday Stockholm 2015 - Building Maintainable and Testable Share...SharePoint Saturday Stockholm 2015 - Building Maintainable and Testable Share...
SharePoint Saturday Stockholm 2015 - Building Maintainable and Testable Share...
 
ESPC14 Social Business Value Demystified
ESPC14 Social Business Value DemystifiedESPC14 Social Business Value Demystified
ESPC14 Social Business Value Demystified
 
Maintainable Testable SharePoint Components SPSBE 2014
Maintainable Testable SharePoint Components SPSBE 2014Maintainable Testable SharePoint Components SPSBE 2014
Maintainable Testable SharePoint Components SPSBE 2014
 
MVP Open Day 2014 - Hacking Human Behaviour
MVP Open Day 2014 - Hacking Human BehaviourMVP Open Day 2014 - Hacking Human Behaviour
MVP Open Day 2014 - Hacking Human Behaviour
 
SPS Stockholm 7 Key Things for Building a Highly-Scalable SharePoint 2013 App
SPS Stockholm 7 Key Things for Building a Highly-Scalable SharePoint 2013 AppSPS Stockholm 7 Key Things for Building a Highly-Scalable SharePoint 2013 App
SPS Stockholm 7 Key Things for Building a Highly-Scalable SharePoint 2013 App
 
7 Key Things for Building a Highly-Scalable SharePoint 2013 App
7 Key Things for Building a Highly-Scalable SharePoint 2013 App7 Key Things for Building a Highly-Scalable SharePoint 2013 App
7 Key Things for Building a Highly-Scalable SharePoint 2013 App
 
Social Business Value Demystified: Real-World Experiences
Social Business Value Demystified: Real-World ExperiencesSocial Business Value Demystified: Real-World Experiences
Social Business Value Demystified: Real-World Experiences
 
BcnDevCon13 - No Designer? No Problem!
BcnDevCon13 - No Designer? No Problem!BcnDevCon13 - No Designer? No Problem!
BcnDevCon13 - No Designer? No Problem!
 
BcnDevCon12 - Una vuelta por Orchard CMS
BcnDevCon12 - Una vuelta por Orchard CMSBcnDevCon12 - Una vuelta por Orchard CMS
BcnDevCon12 - Una vuelta por Orchard CMS
 
BcnDevCon12 - CQRS explicado a mi compañero arquitecto
BcnDevCon12 - CQRS explicado a mi compañero arquitectoBcnDevCon12 - CQRS explicado a mi compañero arquitecto
BcnDevCon12 - CQRS explicado a mi compañero arquitecto
 
CatDotNet - Farmville para SharePoint
CatDotNet - Farmville para SharePointCatDotNet - Farmville para SharePoint
CatDotNet - Farmville para SharePoint
 
Universidad de La Habana - SharePoint, Listas y XSLT
Universidad de La Habana  - SharePoint, Listas y XSLTUniversidad de La Habana  - SharePoint, Listas y XSLT
Universidad de La Habana - SharePoint, Listas y XSLT
 
SharePoint kao razvojna platforma za ASP.NET developere
SharePoint kao razvojna platforma za ASP.NET developereSharePoint kao razvojna platforma za ASP.NET developere
SharePoint kao razvojna platforma za ASP.NET developere
 

JavaScript per a desenvolupadors de C#

  • 2. JavaScript != C# Edin Kapić
  • 3. Qui sóc? @ekapic Edin Kapić Key Consultant (SharePoint) ekapic@pasiona.com SUG.CAT SharePoint User Group Catalunya
  • 4. JavaScript: “With or Without You” Brendan Eich “El pare de la criatura”
  • 5. Com hem arribat fins aquí? 1995 1996 1997 Netscape Navigator 2.0 Internet Explorer 3.0 ECMAScript Mocha/LiveScript JScript
  • 6. 1999 2005 2006 XMLHttpRequest Jesse James Garrett John Resig (OWA Exchange AJAX jQuery 2000)
  • 7. TypeScript 2009 2010 2011 2012 PhoneGap Node.js Windows 8 SharePoint 2013 TypeScript
  • 8. Hem de donar el salt
  • 9. Firebug / IE Dev Tools JSLint JsFiddle Firebug Les eines Lite
  • 10. JavaScript és bo ... • Llenguatge dinàmic • Notació literal potent • “Loose-typed” • “JS is Lisp in C Clothing” (Douglas Crockford) http://bit.ly/Qn0qLi
  • 11. ... però té coses dolentes • Variables globals implícites • Variable hoisting '' == '0' // false • Function hoisting 0 == '' 0 == '0' // // true true false == 'false' // false • Prototype Leaking false == '0' false == undefined // // true false • false == null // false == null == undefined // true ' trn ' == 0 // true
  • 13. • C# • JavaScript – Talla pa – Talla pa – Té mecanismes de – Et pots fer mal seguretat – Es un tros de metall – És complex amb un mànec
  • 14. Bo en C#, dolent en JS • La sintaxi semblant ens pot portar a fer coses que a C# són bones pràctiques • Però poden tenir conseqüències greus a JS • “If it walks like a duck...”
  • 15. JS != C# 1: Tipus de dades Simples Complexos • Number • Object • String • Array • Boolean • Function • Undefined • RegEx • Null • Date
  • 16. JS != C# 2: Variables globals • Tota variable no assignada a un objecte, s’assigna a window • var a = 1; • window.a = 1; http://jsfiddle.net/wQDwN/
  • 17. JS != C# 3: “Variable Hoisting” • Només dos nivells: global i funció – { } no crea àmbit de variable (com a C#) • La variable declarada puja fins el principi de la funció dins la qual està declarada – /*.....*/ var a = 1; http://jsfiddle.net/NE2Km/3/
  • 18. Recomanació • Ser conscient dels tipus de dades • No contaminar window • Declarar variables a dalt de tot (fer el hoisting explícit)
  • 19. JS != C# 4: Wrappers • JS estil C# var myVar = new Object(); var myArr = new Array(); • JS estil pur var myVar = {}; var myArr = [];
  • 20. Recomanació • No fer servir wrappers innecessàriament • Aprendre la notació literal d’objectes de JS
  • 21. JS != C# 5: Truthy / Falsey Valors que donen true Valors que donen false • "0" • false • "false" • 0 • "" • Objectes buits • null • Tota la resta • undefined • NaN
  • 22. Recomanació • Simplifiquem els condicionals if(myVar != "" || myVar != undefined) if(myVar) • Inicialitzem els valors per defecte if(myVar == "") { myVar = "Hola"; } myVar = myVar || "hola";
  • 23. JS != C# 6: L’operador == • Comparació if(false == 0) // true if(false === 0) // false • L’operador == intenta convertir els valors i gairebé segur que no és el que volem
  • 24. Comparació “indeterminista” (false == 0); // true (false == ""); // true (0 == ""); // true (null == false); // false (null == null); // true (undefined == undefined); // true (undefined == null); // true (NaN == null); // false (NaN == NaN); // false
  • 25. Recomanació • Fem servir els operadors === i !== per defecte • No fan conversió de valors • Es comporten com els operadors “habituals” == i != de C#
  • 26. JS != C# 7: Altres “perles” • parseInt() • L’operador + http://jsfiddle.net/tbMX2/ • NaN http://jsfiddle.net/vVgB9/ • “Prototype Leak”
  • 28. Funcions de JavaScript • Són objectes, per tant s’hi poden afegir propietats • Es poden passar com a paràmetres a altres funcions • Hi ha dues maneres de declarar funcions
  • 29. Manera 1: Declaracions • La declaració de la funció es fa així function foo() { /* .... */ } • La funció declarada fa “hoisting” i és disponible a tot el codi JS, independentment de l’ordre http://jsfiddle.net/TQ6LG/
  • 30. Manera 2: Expressions • També podem assignar la funció a una variable mitjançant una expressió: var foo = function () { /* ... */ }; • En aquest cas no hi ha “hoisting” • Podem pensar que una declaració és realment una expressió posada a dalt de tot http://jsfiddle.net/NrQhM/
  • 31. Equivalències • function foo() { /* .... */ } • var foo = function () { /* ... */ }; • var foo = function foo () { /* ... */ }; • var foo = function bar () { /* ... */ }; • Les dues últimes es fan servir per a funcions recursives • Les expressions fan explícita la declaració
  • 32. Codi d’un sol ús • Podem assignar una funció anònimament i no recollir-la • Útil per a executar un codi privat i d’una sola vegada • (function () { /* ... */ })(); http://jsfiddle.net/YAe9S/1/
  • 33. Anidament de funcions • Les funcions són objectes i poden contenir altres funcions var foo = function() { function bar() { /* ... */ } return bar(); }; foo(); http://jsfiddle.net/XUswD/
  • 34. Tancaments (Closures) • El tancament és una manera d’associar la funció amb els seus paràmetres d’entrada – És el manteniment de les variables locals desprès de que la funció hagi retornat var bind = function(x) { return function(y) { return x + y; }; } var plus5 = bind(5); alert(plus5(3)); http://jsfiddle.net/xWAm4/
  • 35. Recomanacions • Dedicar temps per a jugar amb les funcions en JS és imprescindible – Hi ha molts exemples que es poden provar amb JsFiddle • Comprendre els tancaments és important per a entendre els event handlers i encapsulament
  • 38. O estem al dia?
  • 39. Regla #1: Unobtrusive JavaScript • El codi JS s’ha d’afegir sense impactar el HTML de la pàgina <input type="text" name="date“ onchange="validateDate()" /> window.onload = function() { document.getElementById('date').onchange = validateDate; };
  • 40. Regla #2: Modularitat • El nostre codi JS no pot col·lisionar amb qualsevol altre codi JS present • Encapsulem el nostre codi en namespaces • Fem servir try/catch
  • 41. Mètodes d’encapsulament • Cap (objecte window) • Tot privat (funció anònima auto-executada) • Tot públic (objecte literal) • Barreja public/privat (Revealing Module)
  • 42. Objecte literal var car = { status: "off", start: function() { this.status = "on"; }, getStatus: function() { return "the car is " + this.status; } }; car.start(); alert(car.getStatus()); http://jsfiddle.net/DY2Zw/
  • 43. Revealing Module var car = (function() { var pubCar = {}, var innerStatus = "off"; pubCar.start = function() { innerStatus = "on"; } pubCar.status = function() { return "the car is “ + innerStatus; } return pubCar; }()); car.start(); alert(car.status()); http://jsfiddle.net/AUzNT/
  • 44. Recomanacions • Fer servir Revealing Module per a tenir encapsulament totalment controlat per nosaltres • Aïllar-nos d’altres llibreries http://jsfiddle.net/uKuLw/ • Fer servir objecte literal per a fer objectes senzills (p.ex. DTOs) – La sintaxi és diferent
  • 45. Regla #3: Abstracció • Cal abstreure’s dels detalls del navegador concret • Existeixen llibreries que ens unifiquen les diferències: jQuery, AmplifyJS,
  • 46. Llibreries que cal conèixer • MVVM: KnockoutJS • Plantilles: JsRender • Notificacions: SignalR, Toastr • Tests unitaris: QUnitJS • BDD: Jasmine • IoC/DI: Inject, RequireJS
  • 47. KnockoutJS • Possibilita al patró MVVM (Model-View-ViewModel) • Automatitza el binding bidireccional entre el viewmodel (JS) i la vista (HTML) http://knockoutjs.com/ Demo: http://knockoutjs.com/examples/helloWorld.html
  • 48. JsRender • Permet fer “plantilles” d’elements HTML i enllaçar-les amb dades https://github.com/BorisMoore/jsrender Demo: http://borismoore.github.com/jsrender/demos/step-by-step/05_for-tag.html
  • 49. SignalR • Notificacions asíncrones de servidor a client i vice-versa • Útil per a notificacions de sistema a l’usuari • http://signalr.net • Demo: http://zooplet.com/tictactoe/
  • 50. Toastr • Notificacions tipus “torrada” • https://github.com/CodeSeven/toastr • Demo: http://CodeSeven.github.com/toastr
  • 51. QUnitJS http://qunitjs.com/ • Proves unitàries per al codi de JavaScript • Executable dins el navegador Demo: http://jsfiddle.net/booyaa/kdEtk/
  • 52. Jasmine • Proves funcionals amb JavaScript • Descriuen el resultat esperat i poden combinar- se per a formar casos d’ús • https://github.com/pivotal/jasmine • Demo: http://pivotal.github.com/jasmine/
  • 53. Inject / RequireJS • Gestió de dependències entre components JS • https://github.com/linkedin/inject • Demo: http://bit.ly/wu2Pe1 • Alternativa: RequireJS • http://requirejs.org
  • 54. Microsoft TypeScript • És un llenguatge basat en JavaScript • Afegeix la comprovació en temps de compilació de referències, tipus, classes i interfícies • (Trans)compila a JavaScript “pur” • Disponible per a VS2012 • http://www.typescriptlang.org/
  • 55. Resum
  • 56. Recomanacions • Invertir temps en aprendre els principis de JS i experimentar amb els exemples • Repassar el codi existent amb JSLint • Tenir en compte les llibreries de JS com a factor arquitectònic a les aplicacions • JS està aquí per a quedar-s’hi
  • 57. Bibliografia • Douglas Crockford “JavaScript: The Good Parts” (O’Reilly) • Addy Osmani “JavaScript Design Patterns” http://bit.ly/bMyoQ9 • http://jsbooks.revolunet.com/

Notas do Editor

  1. https://getfirebug.com/firebug-lite.js
  2. Undefined = No sé de que m’estàs parlant o no m’has donat cap valor inicialNull = M’has dit que no té cap valor, explícitament Typeof(null) == object (és un bug de JS)Els wrappers també son objects, però és millor no fer-los servir
  3. Validar amb JSLint per a veure el warning