JavaScript Beyond     jQuery     John Wilander                     @johnwilander
shouldilearnjavascript.com                             @johnwilander
Part 1: Typing                 @johnwilander
Java                       TypesPrimitive:byte, short, int, long, float, double,boolean, charThe rest is objects, so calle...
Java               TypesPrimitive:byte, short, int, long, float, double,boolean, charJavaScript Primitive: string, number,...
Java               TypesPrimitive:byte, short, int, long, float, double,boolean, charnot        Strings are       general ...
Java                 TypesPrimitive:Only one typebyte, for numbers, i.e. long, float, double,         short, int,         ...
Java                TypesPrimitive:byte, short, int, long, float, double,boolean, char           Functions are full       ...
Java               TypesPrimitive:byte, short, int, long, float, double,            JavaScriptsboolean, char             v...
Java       Static vs Dynamic TypingStatic typing:String name;         Variables have typesname = ”John”;       Values have...
Dynamic TypingJavaScript             var name = ”John”;               Variables have   Values have types                 n...
Strong vs Weak Typing                        @johnwilander
Strong vs Weak Typing   Strong !== good    Weak !== bad                        @johnwilander
Java         Strong vs Weak Typingint intVar = 4;      Pretty strong typing"" + intVar;         Implicit type conversionin...
Type Safe           ≈no type errors at runtime                            @johnwilander
Johns Conclusion   Java is a statically, strongly typed   language with decent type safetyJavaScript is a dynamically, wea...
Object Orientation                     @johnwilander
Java: Classes & Objects                  Object         Class     Object                               ExecutingSource    ...
JavaScript: Functions,     Object & Prototypes                     Object         Prototype    Object                     ...
JavaScript: Functions,     Object & Prototypes                       Object           Prototype                        Obj...
Keywords in JavaScript                                                                    Statistics from:                ...
Keywords in JavaScript                       Functions,                       functions,                       functions  ...
Java: Extension by   Inheritance      Subclass                 extends       Super        class                       @joh...
Java: Subtyping by   Inheritance       Super        type                 extends       Subtype                       @john...
Through inheritance Java classes get larger in terms of functions           andsmaller in terms of type     (more specific)...
In JavaScript     extension        and     subtypingare separate things                      @johnwilander
Why do we want to      subtype?Because we think in      terms of static typing and   is-a-relations                      @...
Static Typing and             SubtypingJava       public void doPurchase(Item item)                          Accepts Item ...
Dynamic TypingJavaScript             public void doPurchase(Item item)                                                 @jo...
Dynamic TypingJavaScript             public void doPurchase(Item item)                                                 @jo...
Dynamic TypingJavaScript             public void doPurchase(Item item)                                                 @jo...
Dynamic TypingJavaScript             public void doPurchase(Item item)                                                 @jo...
Dynamic TypingJavaScript             function doPurchase(item)__                           Accepts anything               ...
Dynamic TypingJavaScript             function doPurchase(item)__                    Can return anything                   ...
Part 2: To start aJavaScript program                       @johnwilander
<html>            JavaScript and Web<head>  <script src=”js/main.js”></script>  <script>         var JW = {};         // M...
JavaScript and Web<html><head>                                     Script from file in <head>  <script src=”js/main.js”></s...
<html>            JavaScript and Web<head>  <script src=”js/main.js”></script>   Inlined script in <head>  <script>       ...
<html>            JavaScript and Web<head>  <script src=”js/main.js”></script>  <script>         var JW = {};         // M...
<html>            JavaScript and Web<head>  <script src=”js/main.js”></script>  <script>         var JW = {};         // M...
<html>            JavaScript and Web<head>  <script src=”js/main.js”></script>  <script>         var JW = {};         // M...
Good Practice:1. All JavaScript on file.2. All statically loadedJavaScript in one block.                            @johnwi...
Dynamic Loading(function(){ var oldFirstScript =   document.getElementsByTagName(script)[0];     newScript =   document.cr...
OK, thats loading.But I want to start.                       @johnwilander
Java             In the Beginningpublic static void main(String[] args)JavaScript (function(){}()); window.someGlobalFunct...
Self-Invoking FunctionsAnonymous, self-invoking with parameter(function(me) {  // Code}(John));Anonymous, self-invoking wi...
Part 4: Variables                    @johnwilander
JavaScript                  Scope var GLOB = {}; GLOB.func = function(array) {    var local = …;    …    for (var i=0; i<a...
JavaScript                  Scope var GLOB = {}; GLOB.func = function(array) {    var local = …, i, temp;    …    for (i=0...
JavaScript                    Scope var GLOB = {}; GLOB.func = function(array) {    var local = …, i, temp;    …    for (i...
JavaScript              Closure (function(array) {   var i, temp;   …   for (i=0; i<array.length; i++){     …     temp = a...
JavaScript                 Closure (function(array) {   var i, temp;   …   for (i=0; i<array.length; i++){     …     temp ...
JavaScript             Closure Pitfall for(i=0; i<pages.length; i++) {   var page = pages[i];   pageElement.load(page.url,...
JavaScript             Closure Pitfall for(i=0; i<pages.length; i++) {   var page = pages[i];   pageElement.load(page.url,...
JavaScript             Closure Pitfall for(i=0; i<pages.length; i++) {   var page = pages[i];   pageElement.load(page.url,...
JavaScript             Closure Pitfall var page; for(i=0; i<pages.length; i++) {   page = pages[i];   pageElement.load(pag...
JavaScript             Closure Pitfall var page; for(i=0; i<pages.length; i++) {   page = pages[i];   pageElement.load(pag...
JavaScript             Closure Pitfall var page; for(i=0; i<pages.length; i++) {   page = pages[i];   pageElement.load(pag...
Making Use of ClosuresJavaScript var page; for(i=0; i<pages.length; i++) {   page = pages[i];   (function(page) {     page...
Making Use of ClosuresJavaScript var page; for(i=0; i<pages.length; i++) {   page = pages[i];   (function(page) {     page...
With self-invoking functions, scope, and closures we are ready for  the most important design pattern:Part 5: The Crockfor...
JavaScript JW.cache = (function(){}());                                @johnwilander
JavaScript JW.cache = (function(){   return {}; }());                           @johnwilander
JavaScript JW.cache = (function(){   return {     getPatient:       function(personnummer) {             }   }; }());     ...
JavaScript JW.cache = (function(){   var cache = {};   return {     getPatient:       function(personnummer) {            ...
JavaScript JW.cache = (function(){   var cache = {};   return {      getPatient:        function(personnummer) {          ...
JavaScript JW.cache = (function(){   var cache = {};   return {      getPatient:        function(personnummer) {          ...
JavaScript JW.cache = (function(){   var cache = {},       _isValid = function(res) {          }      return {        getP...
JavaScript JW.cache = (function(){   var cache = {},       _isValid(res) {         return !res ? false :          (Date.no...
JavaScript JW.cache = (function(){   var cache = {},       _isValid(res) {         return !res ? false :          (Date.no...
JavaScript Crockford = (function(initParam) {   var privVar1, privVar2,       _privFunc1 = function() {                 },...
Part 6:Named Parameters                   @johnwilander
Java             Method Signaturespublic void execPurchase(int, String,String, boolean, User)JavaScript function execPurch...
Java             Method Signaturesbuilder = new Purchase.Builder();Purchase purchase =     builder.setPrice(9900)     .set...
Part 7: Asynchronous  Module Definition(AMD) with require.js                        @johnwilander
Concatenate and minify              @johnwilander
Concatenate  and minifyYou may want to separatethird party code to be ableto cache it harder.                             ...
Concatenate  and minifyThe goal is to mimimize thenumber of HTTP requests andthe size of data over the wire.              ...
Tools for Concatenation     and Minification• Google Closure Compiler• UglifyJS• require.js  Concatenates and minifies with ...
require.js – import andnamespace in JavaScript                      @johnwilander
require([  "backbone",  "underscore",  "models/CartModel",  "text!templates/CartItem.html"],  function (Backbone, _, CartM...
paths : {        jquery : "vendor/jquery.min",        backbone : "../components/backbone/backbone-min",        underscore ...
File system, like Java packagesrequire([  "backbone",  "underscore",  "models/CartModel",  "text!templates/CartItem.html"]...
require([  "backbone",        Local name, like  "underscore",      dependency injection  "models/CartModel",  "text!templa...
Define new modules   define([     "backbone",     "underscore",     "models/CartModel",     "text!templates/CartItem.html"]...
CartItemView.js                  @johnwilander
index.html without       require.js or the like<head>  <script   src="js/lib/jquery-1.9.0.min.js"></script>  <script   src...
index.html with                require.js<head>  <script data-main="scripts/main" src="scripts/require.js" >  </script></h...
index.html with                require.js<head>  <script data-main="scripts/main" src="scripts/require.js" >  </script></h...
ReferenceDocumentation        Always  developer.mozilla.org       Never  www.w3schools.com         Why?      w3fools.com  ...
The Stream http://javascriptweekly.com/    @javascript_news@BrendanEich @littlecalculist@addy_osmani @addyosmani @paul_iri...
dojo-release-1.8.3.zip 11 Mb  ext-4.1.1a-gpl.zip 45,7 Mb  ext-all.js 1 Mb       yui_3.8.1.zip 28,1 Mb             @joakimk...
SimplifiedDom api     Templates & shimsWidgets       MVC                        @joakimkemeny & @johnwilander
underscoreModernizr jQuery       Simplified              Dom api     Templates               & shims              Widgets  ...
Handlebars                                   MustachSimplifiedDom api     Templates & shimsWidgets       MVC               ...
SimplifiedDom api     Templates & shims                                  Ember                                Backbone     ...
SimplifiedDom api     Templates & shimsWidgets       MVC                                      Spine                        ...
Simplified            Dom api     Templates             & shims            Widgets       MVCBootstrapjQuery UI             ...
Simplified         Dom api     Templates          & shimsExt JSDojoYUI         Widgets       MVC                           ...
All-in-one frameworks arebest suited for newlywritten single-purposeapplications withoutmashup behavior.                  ...
Micro frameworks arebetter if you need tointegrate legacy code, somenifty CMS product, or if youhave logic/content fromthi...
Upcoming SlideShare
Loading in...5
×

JavaScript Beyond jQuery (Jfokus 2013)

1,456

Published on

A presentation on the programming language JavaScript. It covers types, object orientation, variables and scope, closures, the Crockford Module Pattern, loading and executing, imports and namespacing, and more. The language features are compared to Java throughout the slides.

Published in: Technology
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
1,456
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
25
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

JavaScript Beyond jQuery (Jfokus 2013)

  1. 1. JavaScript Beyond jQuery John Wilander @johnwilander
  2. 2. shouldilearnjavascript.com @johnwilander
  3. 3. Part 1: Typing @johnwilander
  4. 4. Java TypesPrimitive:byte, short, int, long, float, double,boolean, charThe rest is objects, so called reference typesJavaScript Primitive: string, number, boolean, function, undefined The rest is object @johnwilander
  5. 5. Java TypesPrimitive:byte, short, int, long, float, double,boolean, charJavaScript Primitive: string, number, boolean, function, undefined @johnwilander
  6. 6. Java TypesPrimitive:byte, short, int, long, float, double,boolean, charnot Strings are general objects, theyre a typeJavaScript Primitive: string, number, boolean, function, undefined @johnwilander
  7. 7. Java TypesPrimitive:Only one typebyte, for numbers, i.e. long, float, double, short, int, no differenceboolean, char between integers or decimalsJavaScript Primitive: string, number, boolean, function, undefined @johnwilander
  8. 8. Java TypesPrimitive:byte, short, int, long, float, double,boolean, char Functions are full objects with their own typeJavaScript Primitive: string, number, boolean, function, undefined @johnwilander
  9. 9. Java TypesPrimitive:byte, short, int, long, float, double, JavaScriptsboolean, char version of uninitialized isJavaScript undefined Primitive: string, number, boolean, function, undefined @johnwilander
  10. 10. Java Static vs Dynamic TypingStatic typing:String name; Variables have typesname = ”John”; Values have typesname = 34; Variables cannot change typeJavaScript Dynamic typing: var name; Variables have no types name = ”John”; Values have types name = 34; Variables change type dynamically @johnwilander
  11. 11. Dynamic TypingJavaScript var name = ”John”; Variables have Values have types no types @johnwilander
  12. 12. Strong vs Weak Typing @johnwilander
  13. 13. Strong vs Weak Typing Strong !== good Weak !== bad @johnwilander
  14. 14. Java Strong vs Weak Typingint intVar = 4; Pretty strong typing"" + intVar; Implicit type conversionintVar + 0.0; Implicit, widening type conv.intVar + (int)0.0; Explicit type conversionintVar + null; Not allowedJavaScript var dynVar = 4; Very weak typing dynVar + ""; Implicit type conversion dynVar + null; Implicit type conversion dynVar + []; Implicit type conversion dynVar + [0]; Implicit type conversion @johnwilander
  15. 15. Type Safe ≈no type errors at runtime @johnwilander
  16. 16. Johns Conclusion Java is a statically, strongly typed language with decent type safetyJavaScript is a dynamically, weakly typed language with decent type safety @johnwilander
  17. 17. Object Orientation @johnwilander
  18. 18. Java: Classes & Objects Object Class Object ExecutingSource Object code Class Singleton @johnwilander
  19. 19. JavaScript: Functions, Object & Prototypes Object Prototype Object ExecutingSource Object code Function Function @johnwilander
  20. 20. JavaScript: Functions, Object & Prototypes Object Prototype Object ExecutingSource Object code Function Anonymous closures Function Modules @johnwilander
  21. 21. Keywords in JavaScript Statistics from: jQuery jQuery.Mobile Prototype Ext JS MooTools Backbone Underscore http://ariya.ofilabs.com/2012/03/most-popular-javascript-keywords.html @johnwilander
  22. 22. Keywords in JavaScript Functions, functions, functions Seldom new Almost never classes as types @johnwilander
  23. 23. Java: Extension by Inheritance Subclass extends Super class @johnwilander
  24. 24. Java: Subtyping by Inheritance Super type extends Subtype @johnwilander
  25. 25. Through inheritance Java classes get larger in terms of functions andsmaller in terms of type (more specific) @johnwilander
  26. 26. In JavaScript extension and subtypingare separate things @johnwilander
  27. 27. Why do we want to subtype?Because we think in terms of static typing and is-a-relations @johnwilander
  28. 28. Static Typing and SubtypingJava public void doPurchase(Item item) Accepts Item or subtypes to Item @johnwilander
  29. 29. Dynamic TypingJavaScript public void doPurchase(Item item) @johnwilander
  30. 30. Dynamic TypingJavaScript public void doPurchase(Item item) @johnwilander
  31. 31. Dynamic TypingJavaScript public void doPurchase(Item item) @johnwilander
  32. 32. Dynamic TypingJavaScript public void doPurchase(Item item) @johnwilander
  33. 33. Dynamic TypingJavaScript function doPurchase(item)__ Accepts anything ... or nothing @johnwilander
  34. 34. Dynamic TypingJavaScript function doPurchase(item)__ Can return anything ... or nothing @johnwilander
  35. 35. Part 2: To start aJavaScript program @johnwilander
  36. 36. <html> JavaScript and Web<head> <script src=”js/main.js”></script> <script> var JW = {}; // More code </script></head><body> <button onclick="document.getElementById(field2).value=document.getElementById(field1).value">Copy text</button> <div> Some information </div> <script> JW.calcPrice = function(price, vat) { //… }; </script> <script src=”http://3rdparty.com/trackUsers.js”></script></body></html> @johnwilander
  37. 37. JavaScript and Web<html><head> Script from file in <head> <script src=”js/main.js”></script> Synchronous loading and <script> var JW = {}; execution // More code </script></head><body> <button onclick="document.getElementById(field2).value=document.getElementById(field1).value">Copy text</button> <div> Some information </div> <script> JW.calcPrice = function(price, vat) { //… }; </script> <script src=”http://3rdparty.com/trackUsers.js”></script></body></html> @johnwilander
  38. 38. <html> JavaScript and Web<head> <script src=”js/main.js”></script> Inlined script in <head> <script> var JW = {}; Synchronous execution // More code </script> before DOM is loaded</head><body> <button onclick="document.getElementById(field2).value=document.getElementById(field1).value">Copy text</button> <div> Some information </div> <script> JW.calcPrice = function(price, vat) { //… }; </script> <script src=”http://3rdparty.com/trackUsers.js”></script></body></html> @johnwilander
  39. 39. <html> JavaScript and Web<head> <script src=”js/main.js”></script> <script> var JW = {}; // More code </script> Script directly in HTML,</head><body> executed on click event <button onclick="document.getElementById(field2).value=document.getElementById(field1).value">Copy text</button> <div> Some information </div> <script> JW.calcPrice = function(price, vat) { //… }; </script> <script src=”http://3rdparty.com/trackUsers.js”></script></body></html> @johnwilander
  40. 40. <html> JavaScript and Web<head> <script src=”js/main.js”></script> <script> var JW = {}; // More code </script></head><body> <button onclick="document.getElementById(field2).value= Inlined script in <body>document.getElementById(field1).value">Copy text</button> <div> Some information Executed when the </div> <script> parser gets here JW.calcPrice = function(price, vat) { //… }; </script> <script src=”http://3rdparty.com/trackUsers.js”></script></body></html> @johnwilander
  41. 41. <html> JavaScript and Web<head> <script src=”js/main.js”></script> <script> var JW = {}; // More code </script></head><body> <button onclick="document.getElementById(field2).value=document.getElementById(field1).value">Copy text</button> <div> Some information Script from file in <body> </div> <script> Loaded and executed synchronously JW.calcPrice = function(price, vat) { //… }; </script> <script src=”http://3rdparty.com/trackUsers.js”></script></body></html> @johnwilander
  42. 42. Good Practice:1. All JavaScript on file.2. All statically loadedJavaScript in one block. @johnwilander
  43. 43. Dynamic Loading(function(){ var oldFirstScript = document.getElementsByTagName(script)[0]; newScript = document.createElement(script), newScript.async = true; newScript.src = js/script.js; oldFirstScript.parentNode.insertBefore( newScript, oldFirstScript);}()); @johnwilander
  44. 44. OK, thats loading.But I want to start. @johnwilander
  45. 45. Java In the Beginningpublic static void main(String[] args)JavaScript (function(){}()); window.someGlobalFunction(); @johnwilander
  46. 46. Self-Invoking FunctionsAnonymous, self-invoking with parameter(function(me) { // Code}(John));Anonymous, self-invoking without parameter(function() { // Code}()); @johnwilander
  47. 47. Part 4: Variables @johnwilander
  48. 48. JavaScript Scope var GLOB = {}; GLOB.func = function(array) { var local = …; … for (var i=0; i<array.length; i++){ … var temp = array[i]; } }; @johnwilander
  49. 49. JavaScript Scope var GLOB = {}; GLOB.func = function(array) { var local = …, i, temp; … for (i=0; i<array.length; i++){ … temp = array[i]; } }; @johnwilander
  50. 50. JavaScript Scope var GLOB = {}; GLOB.func = function(array) { var local = …, i, temp; … for (i=0; There are only two variable scopes: i<array.length; i++){ … Global or local function scope. temp = array[i]; } All local variables are hoisted to }; the top of the function. @johnwilander
  51. 51. JavaScript Closure (function(array) { var i, temp; … for (i=0; i<array.length; i++){ … temp = array[i]; } }([1, 2, 3])); @johnwilander
  52. 52. JavaScript Closure (function(array) { var i, temp; … for (i=0; i<array.length; i++){ … temp =Aarray[i]; its scope and its closure keeps } context during its life span. }([1, 2, 3])); A reference ending up inside the closure (array above) will keep its value inside the closure. @johnwilander
  53. 53. JavaScript Closure Pitfall for(i=0; i<pages.length; i++) { var page = pages[i]; pageElement.load(page.url, function() { launchForm(page.form); }); } @johnwilander
  54. 54. JavaScript Closure Pitfall for(i=0; i<pages.length; i++) { var page = pages[i]; pageElement.load(page.url, function() { launchForm(page.form); }); Callback function since } pageElement.load() is asynchronous @johnwilander
  55. 55. JavaScript Closure Pitfall for(i=0; i<pages.length; i++) { var page = pages[i]; pageElement.load(page.url, function() { page is hoisted and thus gets launchForm(page.form); }); a new value for each iteration } @johnwilander
  56. 56. JavaScript Closure Pitfall var page; for(i=0; i<pages.length; i++) { page = pages[i]; pageElement.load(page.url, page is hoisted and thus gets function() { launchForm(page.form);iteration a new value for each }); } @johnwilander
  57. 57. JavaScript Closure Pitfall var page; for(i=0; i<pages.length; i++) { page = pages[i]; pageElement.load(page.url, function() { launchForm(page.form); }); When the callback is run page } will refer to pages[pages.length-1] or at least another value than intended. @johnwilander
  58. 58. JavaScript Closure Pitfall var page; for(i=0; i<pages.length; i++) { page = pages[i]; pageElement.load(page.url, function() { launchForm(page.form); }); } @johnwilander
  59. 59. Making Use of ClosuresJavaScript var page; for(i=0; i<pages.length; i++) { page = pages[i]; (function(page) { pageElement.load(page.url, function() { launchForm(page.form); } }); })(page); } @johnwilander
  60. 60. Making Use of ClosuresJavaScript var page; for(i=0; i<pages.length; i++) { page = pages[i]; (function(page) { pageElement.load(page.url, function() { launchForm(page.form); } We bind page to a new closure }); })(page); so that the callback refers } correctly @johnwilander
  61. 61. With self-invoking functions, scope, and closures we are ready for the most important design pattern:Part 5: The Crockford Module or Module Pattern @johnwilander
  62. 62. JavaScript JW.cache = (function(){}()); @johnwilander
  63. 63. JavaScript JW.cache = (function(){ return {}; }()); @johnwilander
  64. 64. JavaScript JW.cache = (function(){ return { getPatient: function(personnummer) { } }; }()); @johnwilander
  65. 65. JavaScript JW.cache = (function(){ var cache = {}; return { getPatient: function(personnummer) { } }; }()); @johnwilander
  66. 66. JavaScript JW.cache = (function(){ var cache = {}; return { getPatient: function(personnummer) { var res=cache[personnummer]; // Check if fresh // Return } }; }()); @johnwilander
  67. 67. JavaScript JW.cache = (function(){ var cache = {}; return { getPatient: function(personnummer) { var res=cache[personnummer]; if(_isValid(res)) { return res.patient; } else { // Handle cache miss } } }; }()); @johnwilander
  68. 68. JavaScript JW.cache = (function(){ var cache = {}, _isValid = function(res) { } return { getPatient: function(personnummer) { var res=cache[personnummer]; if(_isValid(res)) { return res.patient; } else { // Handle cache miss } } @johnwilander
  69. 69. JavaScript JW.cache = (function(){ var cache = {}, _isValid(res) { return !res ? false : (Date.now() - res.timestamp) <= 60000; // One minute } return { getPatient: function(personnummer) { var res=cache[personnummer]; if(_isValid(res)) { return res.patient; } else { // Handle cache miss @johnwilander
  70. 70. JavaScript JW.cache = (function(){ var cache = {}, _isValid(res) { return !res ? false : (Date.now() - res.timestamp) <= 60000; // One minute } return { We can have (closure) private variables and functions getPatient: function(personnummer) { var res=cache[personnummer]; if(_isValid(res)) { return res.patient; } else { // Handle cache miss @johnwilander
  71. 71. JavaScript Crockford = (function(initParam) { var privVar1, privVar2, _privFunc1 = function() { }, _privFunc2 = function() { }; return { pubVar1: ”value”, pubFunc1: function() { } }; }(initParam)); @johnwilander
  72. 72. Part 6:Named Parameters @johnwilander
  73. 73. Java Method Signaturespublic void execPurchase(int, String,String, boolean, User)JavaScript function execPurchase(price, item, discountCode, wantsSpam, user) @johnwilander
  74. 74. Java Method Signaturesbuilder = new Purchase.Builder();Purchase purchase = builder.setPrice(9900) .setItem(”cap”).wantsSpam(false) .setUser(user).build();JavaScript function execPurchase(purchase) { purchase.price … purchase.item … purchase.wantsSpam … purchase.user … @johnwilander
  75. 75. Part 7: Asynchronous Module Definition(AMD) with require.js @johnwilander
  76. 76. Concatenate and minify @johnwilander
  77. 77. Concatenate and minifyYou may want to separatethird party code to be ableto cache it harder. @johnwilander
  78. 78. Concatenate and minifyThe goal is to mimimize thenumber of HTTP requests andthe size of data over the wire. @johnwilander
  79. 79. Tools for Concatenation and Minification• Google Closure Compiler• UglifyJS• require.js Concatenates and minifies with Closure Compiler or UglifyJS @johnwilander
  80. 80. require.js – import andnamespace in JavaScript @johnwilander
  81. 81. require([ "backbone", "underscore", "models/CartModel", "text!templates/CartItem.html"], function (Backbone, _, CartModel, cartItemTemplate) { // Code dependent on Backbone etc}); @johnwilander
  82. 82. paths : { jquery : "vendor/jquery.min", backbone : "../components/backbone/backbone-min", underscore : "../components/underscore/underscore" } main.jsrequire([ "backbone", "underscore", "models/CartModel", "text!templates/CartItem.html"], function (Backbone, _, CartModel, cartItemTemplate) { // Code dependent on Backbone etc}); @johnwilander
  83. 83. File system, like Java packagesrequire([ "backbone", "underscore", "models/CartModel", "text!templates/CartItem.html"], function (Backbone, _, CartModel, cartItemTemplate) { // Code dependent on Backbone etc}); @johnwilander
  84. 84. require([ "backbone", Local name, like "underscore", dependency injection "models/CartModel", "text!templates/CartItem.html"], function (Backbone, _, CartModel, cartItemTemplate) { var model = new CartModel();}); @johnwilander
  85. 85. Define new modules define([ "backbone", "underscore", "models/CartModel", "text!templates/CartItem.html"], function (Backbone, _, CartModel, cartItemTemplate) { var CartItemView = …; … return CartItemView; }); @johnwilander
  86. 86. CartItemView.js @johnwilander
  87. 87. index.html without require.js or the like<head> <script src="js/lib/jquery-1.9.0.min.js"></script> <script src="js/lib/jquery-encoder-0.1.0.js"></script> <script src="js/base.js"></script> <script src="js/JW/util/util.js"></script> <script src="js/JW/personnummer/Personnummer.js"></script> <script src="js/JW/patient/Patient.js"></script> … <script src="js/JW/cache/cache.js"></script> <script src="js/JW/proxy/proxy.js"></script> <script src="js/JW/gui/gui.js"></script></head> … manually, in the right order. @johnwilander
  88. 88. index.html with require.js<head> <script data-main="scripts/main" src="scripts/require.js" > </script></head> @johnwilander
  89. 89. index.html with require.js<head> <script data-main="scripts/main" src="scripts/require.js" > </script></head> require.config({ … paths : { jquery : "vendor/jquery.min", backbone : "../components/backbone/backbone-min", underscore : "../components/underscore/underscore" } }); require(["app"], function (App) { App.start(); }); main.js @johnwilander
  90. 90. ReferenceDocumentation Always developer.mozilla.org Never www.w3schools.com Why? w3fools.com @johnwilander
  91. 91. The Stream http://javascriptweekly.com/ @javascript_news@BrendanEich @littlecalculist@addy_osmani @addyosmani @paul_irish @badass_js @rwaldron @slicknet @kangax @unscriptable @sthlmjs @johnwilander
  92. 92. dojo-release-1.8.3.zip 11 Mb ext-4.1.1a-gpl.zip 45,7 Mb ext-all.js 1 Mb yui_3.8.1.zip 28,1 Mb @joakimkemeny & @johnwilander
  93. 93. SimplifiedDom api Templates & shimsWidgets MVC @joakimkemeny & @johnwilander
  94. 94. underscoreModernizr jQuery Simplified Dom api Templates & shims Widgets MVC @joakimkemeny & @johnwilander
  95. 95. Handlebars MustachSimplifiedDom api Templates & shimsWidgets MVC @joakimkemeny & @johnwilander
  96. 96. SimplifiedDom api Templates & shims Ember Backbone angularWidgets MVC @joakimkemeny & @johnwilander
  97. 97. SimplifiedDom api Templates & shimsWidgets MVC Spine @joakimkemeny & @johnwilander
  98. 98. Simplified Dom api Templates & shims Widgets MVCBootstrapjQuery UI @joakimkemeny & @johnwilander
  99. 99. Simplified Dom api Templates & shimsExt JSDojoYUI Widgets MVC @joakimkemeny & @johnwilander
  100. 100. All-in-one frameworks arebest suited for newlywritten single-purposeapplications withoutmashup behavior. @joakimkemeny & @johnwilander
  101. 101. Micro frameworks arebetter if you need tointegrate legacy code, somenifty CMS product, or if youhave logic/content fromthird parties.Micro frameworks dont”take over” you application. @joakimkemeny & @johnwilander
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×