JavaScript Primer

1,207 views
1,114 views

Published on

The second-half of the php|tek 2012 tutorial session "HTML5 and JavaScript"

Published in: Technology, Design
0 Comments
4 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,207
On SlideShare
0
From Embeds
0
Number of Embeds
5
Actions
Shares
0
Downloads
55
Comments
0
Likes
4
Embeds 0
No embeds

No notes for slide

JavaScript Primer

  1. 1. HTML5 and JavaScript Part DeuxThursday, July 5, 12
  2. 2. Daniel Cousineau @dcousineauThursday, July 5, 12
  3. 3. HistoryThursday, July 5, 12
  4. 4. Mocha April 1995 LiveScript JavaScript Brendan Eich CTO, Mozilla Corp.Thursday, July 5, 12
  5. 5. JScript JavaScript ECMAScript ActionScriptThursday, July 5, 12
  6. 6. BasicsThursday, July 5, 12
  7. 7. Data Types • number • string • boolean • object • null • NaN • undefinedThursday, July 5, 12
  8. 8. Strings • Are Objects, have methodsThursday, July 5, 12
  9. 9. Strings "Foo" + "Bar"; //"FooBar" var str = "Lorem Ipsum Dolor Sit Amet"; str.toLowerCase(); //"lorem ipsum dolor sit amet" str.toUpperCase(); //"LOREM IPSUM DOLOR SIT AMET" str.split(" "); //["Lorem", "Ispum", "Dolor", "Sit", "Amet"] str.substring(6,9); //"Ips" new String("Lorem Ipsum Dolor Sit Amet") == str; //trueThursday, July 5, 12
  10. 10. String to Number parseInt("56"); //56 parseInt("42.567"); //42 parseInt("asdf"); //NaN parseInt("5a6"); //5 parseFloat("24.68"); //24.68 parseFloat("asdf"); //NaN parseFloat("24a"); //24Thursday, July 5, 12
  11. 11. Objects • “Dictionary” / “Associative Array” • Key: Value or Key: Value • Without : A-Z0-9 only • Does not keep intrinsic ordering • Accessed keys using . (dot) or [] notationThursday, July 5, 12
  12. 12. Objects var object = { foo: value, complex key: 0, bar: { nested: true } }; object.foo; //value object.[complex key]; //0 object.bar.nested; //true object.bar[nested]; //true object[bar].nested; //true object[bar][nested]; //trueThursday, July 5, 12
  13. 13. in or hasOwnProperty() • Tough call: • .hasOwnProperty() more consistent • in checks inherited properties • Used in for loopThursday, July 5, 12
  14. 14. in var test = { foo: value, bar: value, baz: value } for (var key in test) { console.log(key + ": " + test[key]); } //PRINTS: //foo: value //bar: value //baz: valueThursday, July 5, 12
  15. 15. Arrays • Special object • Numerical keys only • Keeps intrinsic ordering • Short ([]) and Long (new Array()) syntaxThursday, July 5, 12
  16. 16. Arrays var arrayShort = [ one, two ]; arrayShort[2] = three; var arrayLong = new Array(); arrayLong[0] = one; arrayLong[1] = two; arrayLong[2] = three; //arrayShort: ["one", "two", "three"] //arrayLong: ["one", "two", "three"]Thursday, July 5, 12
  17. 17. Arrays var arr = [1,2,3,4,6]; arr.indexOf(2); //1 arr.join(:); //"1:2:3:4:6" arr.pop(); //6 //[1,2,3,4] arr.push(7); //5 //[1,2,3,4,7] arr.reverse(); //[7,4,3,2,1] arr.shift(); //1 //[2,3,4,7] arr.unshift(8); //5 //[8,2,3,4,7] arr.slice(1); //[2,3,4,7] arr.slice(1,3); //[2,3] arr.slice(-3); //[3,4,7] arr.slice(-3,-1); //[3,4]Thursday, July 5, 12
  18. 18. Arrays var arr1 = [1,2,3]; var arr2 = [3,4,5]; arr1.concat(arr2); //[1,2,3,3,4,5]Thursday, July 5, 12
  19. 19. delete • Removes element from an object • “Removes element from an array” • Not really, just sets it to undefinedThursday, July 5, 12
  20. 20. Functions • Are Objects as well • “Elevated” • You can use a named function before it is defined in code • Function definitions are elevated to the topThursday, July 5, 12
  21. 21. Functions function Foo() { //... } Foo(); //valid Bar(); //valid function Bar() { //... }Thursday, July 5, 12
  22. 22. Functions function Foo() { } Foo.bar = "value"; bar in Foo; //true Foo.bar == "value"; //trueThursday, July 5, 12
  23. 23. Function Arguments • No way to assign default arguments • But arguments are not required • If an argument is not specified, it is set to undefinedThursday, July 5, 12
  24. 24. arguments • A special variable found inside a function • A not-quite array object containing all the function argumentsThursday, July 5, 12
  25. 25. arguments function sum() { var x = 0; for (var i = 0; i < arguments.length; ++i) { x += arguments[i]; } return x; } sum(1, 2, 3); //6Thursday, July 5, 12
  26. 26. typeof • Determines a variables type • Returns a stringThursday, July 5, 12
  27. 27. typeof typeof true; //"boolean" typeof 12; //"number" typeof "string"; //"string" typeof []; //"object" typeof {}; //"object" typeof NaN; //"number" typeof null; //"object" typeof undefined; //"undefined" function Foo() {} typeof Foo; //"function"Thursday, July 5, 12
  28. 28. Comparison • a == b / a != b • A and B compared by value alone • 1 == “1” evaluates to true • a === b / a !== b • A and B compared by value and by type • 1 === “1” evaluates to falseThursday, July 5, 12
  29. 29. window, document • Built in, global, Objects • window • Provides access to the browser window • The “global” object: foo === window.foo • Things like window.location.href, etc • document • Provides access to the current DOMThursday, July 5, 12
  30. 30. ClosuresThursday, July 5, 12
  31. 31. Closures • First-Class • Can assign functions to variables, pass as arguments and return as values • Anonymous • Not required to have a name • A function that “closes over” variables defined outside itselfThursday, July 5, 12
  32. 32. Closures function Foo() { var count = 0; return function() { count = count + 1; return count; }; } var bar = Foo(); bar(); //1 bar(); //2 bar(); //3Thursday, July 5, 12
  33. 33. Closures function createAdder(amount) { return function(input) { return input + amount; }; } var add2 = createAdder(2); add2(2); //4 add2(8); //10 var add3 = createAdder(3); add3(3); //6 add3(7); //10Thursday, July 5, 12
  34. 34. Module Pattern (function(exports, undefined){ //ALL your code here var localVar = "bar" globalVar = "baz"; exports.foo = "bat"; })(window); alert(localVar); //error alert(globalVar); //"baz" alert(window.globalVar); //"baz" alert(foo); //"bat" alert(window.foo); //"bat" BEWARE: export (singular) is a reserved word in SafariThursday, July 5, 12
  35. 35. ScopingThursday, July 5, 12
  36. 36. Global & Local • Functions are the only way to create new scopes • Variables defined with var are local • Variables defined without var are global • Global variables are members of windowThursday, July 5, 12
  37. 37. Global & Local var outerScope = 10; var outerScope2 = 10; function Foo() { var outerScope = 20; var innerScope = 20; globalVariable = 30; outerScope2 = 40; } Foo(); alert(outerScope); //10 alert(outerScope2); //40 alert(innerScope); //error alert(globalVariable); //30Thursday, July 5, 12
  38. 38. Lexical Scoping function Foo() { function Foo() { var baz = 1; var baz = 1; return Bar(); function Bar() { } return baz; } function Bar() { return baz; return Bar(); } } Foo(); //baz is not defined Foo(); //1Thursday, July 5, 12
  39. 39. Hoisting foo(); //called foo! Named functions are parsed and made available before general function foo() { evaluation (thus “hoisted” to the top console.log(called foo!); } of the file). foo(); //called foo! Anonymous functions, or functions assigned to variables, require evaluation before they become bar(); //undefined is not a function available var bar = function() { console.log(called bar!); } bar(); //called bar!Thursday, July 5, 12
  40. 40. Practical: Currying function makeAdder(a) { return function(b) { return a+b; } } var two = makeAdder(2); two(1); //3 two(2); //4 two(3); //5Thursday, July 5, 12
  41. 41. thisThursday, July 5, 12
  42. 42. this • Trips everyone up • Special variable used within a function • Refers to the “contextual object” • Changes based on where a function executesThursday, July 5, 12
  43. 43. this var Foo = { bar: "bar", baz: function() { return this.bar; } }; Foo.baz(); //"bar" Foo.bar = "bat"; Foo.baz(); //"bat" var baz = Foo.baz; baz(); //undefinedThursday, July 5, 12
  44. 44. this var Foo = { bar: "bar", baz: function() { return this.bar; } }; Foo.bat = function() { return this.bar + "bat"; }; Foo.bat(); //"barbat"Thursday, July 5, 12
  45. 45. call & apply • Methods in the function prototype • Change the context in which a function executes!Thursday, July 5, 12
  46. 46. call & apply var Foo = { bar: "bar", baz = function(param1, param2) { return this.bar + param1 + param2; } }; var Foo2 = { bar: "123" }; Foo.baz("baz", "bat"); //"barbazbat" Foo.baz.apply(Foo2, "baz", "bat"); //"123bazbat" Foo.baz.call(Foo2, ["baz", "bat"]); //"123bazbat"Thursday, July 5, 12
  47. 47. Practical: Binding function bind(func, context) { return function() { return func.call(context, arguments); } }Thursday, July 5, 12
  48. 48. ExceptionsThursday, July 5, 12
  49. 49. Exceptions • All errors are thrown • Classic try...catch...finally blocksThursday, July 5, 12
  50. 50. Exceptions try { funcDoesNotExist(); } catch (e) { alert(e); //ReferenceError: funcDoesNotExist is not defined } finally { //Always Executes }Thursday, July 5, 12
  51. 51. Exceptions function Foo() { throw new Error("Message"); } function Bar() { throw "Message"; } try { Foo(); } catch (e) { e.message == "Message"; //true } try { Bar(); } catch (e) { e == "Message"; //true }Thursday, July 5, 12
  52. 52. PrototypeThursday, July 5, 12
  53. 53. OOP... Kinda... • Almost no real difference between a dictionary and an object • Named Functions double as object constructors • Function objects contain a prototype dictionary that is copied to instance when using newThursday, July 5, 12
  54. 54. OOP... Kinda... Foo function Foo() { //The "Constructor" } ‣ bar ‣ prototype Foo.bar = function() { ‣ baz //A "Static" Function ‣ constructor } ‣ __proto__ Foo.prototype.baz = function() { //A "Method" };Thursday, July 5, 12
  55. 55. new instance var instance = new Foo(); instance.baz(); //works ‣ __proto__ instance.bar(); //error ‣ baz ‣ constructor Foo.bar(); //works ‣ __proto__ Foo.baz(); //error ‣ ... Foo.prototype.baz(); //worksThursday, July 5, 12
  56. 56. new instance instance.bat = function() { /* ... */ } ‣ bat ‣ __proto__ instance.bat(); //works ‣ baz ‣ constructor Foo.bat(); //error ‣ __proto__ Foo.prototype.bat(); //error ‣ ...Thursday, July 5, 12
  57. 57. Overriding Prototype function Foo(baz) { this.baz = baz; } Foo.prototype.bar = function() { return this.baz; }; var foo1 = new Foo(1); var foo2 = new Foo(2); foo1.bar(); //1 foo2.bar(); //2 Foo.prototype.bar = function() { return this.baz * 2; }; foo1.bar(); //2 foo2.bar(); //4Thursday, July 5, 12
  58. 58. AsynchronousThursday, July 5, 12
  59. 59. Asynchronous • setTimeout, setInterval allow you to have code executing asynchronously while other code executesThursday, July 5, 12
  60. 60. setInterval var id = setInterval(function() { //Code to execute every 1000 milliseconds }, 1000); //clearInterval(id); to stopThursday, July 5, 12
  61. 61. setTimeout var id = setTimeout(function() { //Code to execute after 1000 milliseconds have passed }, 1000); //clearTimeout(id); to cancelThursday, July 5, 12
  62. 62. setInterval() setTimeout()Thursday, July 5, 12
  63. 63. Nifty Trick setTimeout(function() { //Code to run in parallel //while the code after is //executed. }, 1); //Code here will execute immediately //without waiting on the aboveThursday, July 5, 12
  64. 64. DOMThursday, July 5, 12
  65. 65. DOM • Document Object Model • API to interact with the HTML/XHTML documentThursday, July 5, 12
  66. 66. DOM: Selection document Basic selection methods in native .getElementById(foo); DOM document .getElementsByClassName(.bar); document .getElementsByTagName(script);Thursday, July 5, 12
  67. 67. Thursday, July 5, 12
  68. 68. DOM: Creation var paragraph = document.createElement(p); var content = document.createTextNode("Lorem Ipsum"); paragraph.appendChild(content); paragraph.classList.add(my-class); document.getElementsByTagName(body)[0].appendChild(paragraph);Thursday, July 5, 12
  69. 69. Thursday, July 5, 12
  70. 70. Async Script Loading var script = Creates a script element, set its src document.createElement(script); and async properties script.src = "http://path.to/script.js"; script.async = true; Insert the script before the first script tag in the body of the var s = document document .getElementsByTagName(script)[0]; s.parentNode .insertBefore(script, s);Thursday, July 5, 12
  71. 71. DOM https://developer.mozilla.org/en/Gecko_DOM_ReferenceThursday, July 5, 12
  72. 72. DebuggingThursday, July 5, 12
  73. 73. Chrome/Safari Devel. ToolsThursday, July 5, 12
  74. 74. Firefox FireBugThursday, July 5, 12
  75. 75. Console • Provided by major browser vendors • Useful for viewing logs, exceptions, real-time data dumping, and code execution within the current context • Your best friend • Though older IEs FREAK OUT when you leave it in, remove before deploy!Thursday, July 5, 12
  76. 76. console • Ditch alert(), this is your var_dump() • console.log(arg1, arg2, ...) • console.info Same as log • console.warn Icon indicator • console.error Stack traceThursday, July 5, 12
  77. 77. BEWARE • console.log is not blocking • In heavily asynchronous applications, sometimes value displayed is not value at the moment of the call • Your if/else conditionals will work yet console.log will return something that should cause them to failThursday, July 5, 12
  78. 78. Network • Display all network requests via a gantt-like graph • Shows browser-initiated (css, images, etc) and script initiated (ajax) alike • Along with both request and response headersThursday, July 5, 12
  79. 79. Script • Provides a familiar break-point debugging workflowThursday, July 5, 12
  80. 80. Coding StylesThursday, July 5, 12
  81. 81. Coding Styles • Mostly your standard C based style techniques • Special considerations • Semi-colons? No semi-colons? • Leading , ? • Prototype Definition?Thursday, July 5, 12
  82. 82. Comma Style var dict = { var dict = { foo: bar, foo: bar baz: bat , baz: bat }; };Thursday, July 5, 12
  83. 83. var Declaration Style var foo; var foo var bar; , bar var baz; , baz;Thursday, July 5, 12
  84. 84. Prototype Style function Foo() { function Foo() { } } Foo.prototype.bar = function(){ Foo.prototype = { bar: function() { }; } }Thursday, July 5, 12
  85. 85. Code Quality Tools • JSLint http://www.jslint.com/ • By Crockford, extremely strict and inflexible. Code like Crockford! • JSHint http://www.jshint.com/ • Fork, more flexible according to your own rules and preferencesThursday, July 5, 12
  86. 86. Common TechniquesThursday, July 5, 12
  87. 87. Safe Extension App = window.App || {}; Grab global App dictionary, or create if not found App.utility = function() { //Globally available, no //conflicts Add a function utility, is now }; globally accessible without fearing collision with other functioned similarly namedThursday, July 5, 12
  88. 88. IIFE (function(exports){ Immediately exports.foo = function() { Invoked Function }; Expression var bar = function() { Function is defined then }; immediately invoked. Closest thing })(window); to a namespace/module system. foo(); //success bar(); //not found! Prevents variable leakage into outer scopesThursday, July 5, 12
  89. 89. Pro-Tip • Create an application namespace as a dictionary in the global scope • Add in any global level configuration valuesThursday, July 5, 12
  90. 90. JSONThursday, July 5, 12
  91. 91. 2001 JSON Douglas Crockford AwesomeThursday, July 5, 12
  92. 92. JSON • JavaScript Object Notation • Serialization format that is basically JavaScript code minus comments • Can be eval()’ed • But don’t! Use JSON2.js or equivalent • Minimal overhead compared to XML • No parsers required, native mappingThursday, July 5, 12
  93. 93. JSON {"menu": { <menu id="file" value="File"> "id": "file", <popup> "value": "File", <menuitem value="New" "popup": { onclick="CreateNewDoc()" /> "menuitem": [ <menuitem value="Open" {"value": "New", onclick="OpenDoc()" /> "onclick": "CreateNewDoc()"}, <menuitem value="Close" {"value": "Open", onclick="CloseDoc()" /> "onclick": "OpenDoc()"}, </popup> {"value": "Close", </menu> "onclick": "CloseDoc()"} ] } }}Thursday, July 5, 12
  94. 94. BREAK HAMMER TIMEThursday, July 5, 12
  95. 95. jQueryThursday, July 5, 12
  96. 96. January 2006 jQuery John Resig Author, jQueryThursday, July 5, 12
  97. 97. jQuery • Cross-browser JavaScript library • Simplifies and normalizes DOM, AJAX, etc. • Centers around using extended CSS selectors to grab an element(s)Thursday, July 5, 12
  98. 98. Selectors • Superset of CSS3 selectors • Custom Pseudo-Classes • Filters in jQuery parlanceThursday, July 5, 12
  99. 99. Selectors • $(selector) returns jQuery object for chaining purposes • Chained methods will apply to all results if selector matches multiple elementsThursday, July 5, 12
  100. 100. Selectors $("p:not(.special)") Finds all p tags that do not have the .addClass("semi-special"); class special, and adds the class semi-specialThursday, July 5, 12
  101. 101. Selectors $(select option:selected).val(); Gets the value of the selected option in a select boxThursday, July 5, 12
  102. 102. Testing Elements $(.foo).is(:visible); Tests matched element against selector, in this case the jQuery ‘visible’ selectorThursday, July 5, 12
  103. 103. Custom Filters • jQuery provides the ability to create custom filters • :radio, :hidden, etc are custom filters provided by defaultThursday, July 5, 12
  104. 104. jQuery $("#foo") <div id="foo"></div> .html("<strong>bar</strong> baz"); <div id="foo"> <strong>bar</strong> baz </div>Thursday, July 5, 12
  105. 105. Chaining • Most all jQuery methods are chain-able • If $() returns > 1 element, methods invoked will apply to all matchedThursday, July 5, 12
  106. 106. Chaining $(ul.first) Find all ul with class first .find(.foo) .css(color, red) .end().find(.bar) Find elements of class foo that are .css(color, blue) children of the top level matched set .end(); Apply the css style of color:red; Pop the matching of .foo off the jQuery object Find elements of class bar that are children of the top level matched set (ul.first) Apply the css style of color:blue;Thursday, July 5, 12
  107. 107. Events • jQuery wraps an event handling system • Handles browser events, AJAX events, and custom eventsThursday, July 5, 12
  108. 108. Events $(document).ready(function() { //Only execute when the document fires //its onready event (page is done loading) }); $(document).bind(ready, function() { //Equivalent to the above }); $(function() { //Shortcut, equivalent to the above });Thursday, July 5, 12
  109. 109. Events $(img).hover(function(){ //Do something when user hovers over //any img tag });Thursday, July 5, 12
  110. 110. Events • Event functions have the matched element from jQuery bound as thisThursday, July 5, 12
  111. 111. jQuery $(a.foo).click(function(){ Listen for click on a.foo var $this = $(this) , href = $this.href(); this will be the specific a.foo //href will be the clicked element that was clicked //links href });Thursday, July 5, 12
  112. 112. Live Events • Events using .bind are bound to the specific element at the specific point in time it was bound • New elements that match will not be included • Using .on or .off produces a delegate listener that scans for bubbled events that match a selector • New elements that match said selector WILL be includedThursday, July 5, 12
  113. 113. Live Events $(.grandparent) All a tags that exist at some point .on(click, a, function(e){ as a descendant of .grandparent var $target = $(e.target); will trigger this event on click //$target will *usually* //be the a tag, though Any future a tags that are added as //sometimes it will be a a descendant of .grandparent //nested tag }); will trigger this event on clickThursday, July 5, 12
  114. 114. Proxy function Foo() {} Create a Prototype object for example purposes, then create new Foo.prototype.baz = function() {}; instance. Foo.prototype.bar = function() { this.baz(); }; The first click handler will fail. The keyword this will not be a var instance = new Foo(); reference to the instance of Foo as expected, but a reference to the $(element).click(instance.bar); matched DOM element that was $(element).click( clicked. jQuery.proxy( instance.bar, jQuery.proxy() will wrap your instance function such that further ); invocations will use the context you ); set for thisThursday, July 5, 12
  115. 115. Animation $(.button).click(function(){ When .button is clicked, fade out $(img.preview) img.preview over 600 milliseconds .fadeOut(600, function() { and then remove it from the DOM $(this).remove(); }); });Thursday, July 5, 12
  116. 116. animate $(#book).animate({ Animate the following attributes opacity: 0.25, over the course of 5 seconds: left: +=50, opacity to 25% height: toggle }, move to the right 50px 5000, toggle height function() { // Animation complete. } );Thursday, July 5, 12
  117. 117. DOM Creation / Insertion • Super easy! Provide html tag to $() and jQuery will create the element and return it wrapped in jQuery • Second parameter is dictionary for properties • Then use methods like .append() to insertThursday, July 5, 12
  118. 118. DOM Creation $(<div>); Creates a DIV tag $(<input type="text" />); Creates an input (text) tag $(<span>, { class: foo Creates a span with the class of foo });Thursday, July 5, 12
  119. 119. DOM Override $(#foo) Replaces the content of #foo with: .html("<strong>Testing</strong>"); Testing $(#bar) .text("<strong>Testing</strong>"); Replaces the content of #bar with: <strong>Testing</strong>Thursday, July 5, 12
  120. 120. DOM Insertion $(<div>) Insertion (inside): .appendTo($(#foo)); -append $(#foo) -appendTo .append($(<span>)); -html -prepend $(<div>) -prependTo .prependTo($(#bar)); -text Insertion (outside): $(#baz) .after($(<span>)); -after -before $(<div>) -insertAfter .insertBefore($(#baz)); -insertBeforeThursday, July 5, 12
  121. 121. AJAX • Asynchronous JavaScript And XML • Though never use XML, use JSON • jQuery has an AJAX library • Wraps all the different browser quirks • IE is weirdThursday, July 5, 12
  122. 122. AJAX $.ajax({ url: "test.php", success: function(data){ $(div.status).addClass("done") .html(data); } });Thursday, July 5, 12
  123. 123. Cross-Domain • Browser will not fire AJAX requests to a domain outside the one said JavaScript was loaded from • If you include http://sub.domain.tld/file.js, it cannot make AJAX requests to http:// another.tld/ • It can make requests to http://domain.tld/Thursday, July 5, 12
  124. 124. JSONp • Workaround to cross-domain • Load like it is a javascript file (create an inject a script tag into the DOM) • Response is a function (defined by a callback GET parameter) that executes and returns valueThursday, July 5, 12
  125. 125. JSONp domain.tld/api.json domain.tld/api.jsonp?callback=callback ["api", "response"] callback(["api", "response"]);Thursday, July 5, 12
  126. 126. JSONp $.ajax({ dataType: jsonp , url: http://search.twitter.com/search.json , data: { q: "#tek12" } , success: function(resp) { jQuery.each(resp.results, function(id, tweet){ $(<div>, { class: tweet }) .append($(<strong>, { class: user , text: @ + tweet.from_user })) .append($(<span>,{ class: text , text: tweet.text })) .appendTo($(#tweets)); }); } });Thursday, July 5, 12
  127. 127. Extending: Custom Filters $.expr[:].inline = function(elem){ Create new :inline filter (checks var $elem = $(elem) if display is set to inline) , disp = $elem.css(display); return disp === inline; Works like any other native inline }; $(div a:inline) .css(color, red); $(span:not(:inline)) .css(color, blue)Thursday, July 5, 12
  128. 128. (function($, global, undefined){ var defaults = { foo: "bar" }; var methods = { init: function(options) { // Merge user defined options options = $.extend(true, {}, defaults, options); return this; }, method: function() { }, } $.fn.foo = function(method) { if( methods[method] ) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method == object || !method) { return methods.init.apply(this, arguments); } else { $.error(Method + method + does not exist); return undefined; } } })(jQuery, window);Thursday, July 5, 12
  129. 129. Resources http://api.jquery.com/Thursday, July 5, 12
  130. 130. Underscore.jsThursday, July 5, 12
  131. 131. 2009 Underscore.js DocumentCloudThursday, July 5, 12
  132. 132. Underscore.js • Functional, self-contained micro library • Uses chaining for expressiveness • Does not inject methods into native objects!Thursday, July 5, 12
  133. 133. Functional Programming • Functions are mappings between input and output • No side-effects • Input A always results in output B • No OOP • LISP, Haskell, ErlangThursday, July 5, 12
  134. 134. Underscore.js • _(coll).method(arg1, ..) • _.method(coll, arg1, ..)Thursday, July 5, 12
  135. 135. Underscore.js Collections •union •has •each •intersection •isEqual •map •difference •isEmpty •reduce •uniq •isElement •reduceRight •zip •isArray •find •indexOf •isObject •filter •lastIndexOf •isArguments •reject •range •isFunction •all Functions •isString •any •bind •isNumber •include •bindAll •isFinite •invoke •memoize •isBoolean •pluck •delay •isDate •max •defer •isRegExp •min •throttle •isNaN •sortBy •debounce •isNull •groupBy •once •isUndefined •sortedIndex •after Utility •shuffle •wrap •noConflict •toArray •compose •identity •size Objects •times Arrays •keys •mixin •first •values •uniqueId •initial •functions •escape •last •extend •result •rest •pick •template •compact •defaults Chaining •flatten •clone •chain •without •tap •valueThursday, July 5, 12
  136. 136. Map var inp = [1, 2, 3] Maps function to each element in , out = _.map(inp, function(n){ the input collection return n*2; }); //out = [2, 4, 6]Thursday, July 5, 12
  137. 137. Reduce var inp = [1, 2, 3]; Reduces collection to a single value. mem is the initial state, each _(inp).reduce(function(mem, n){ return mem + n; successive iteration must be }); returned //Iter 0: mem = 1 | n = 2 //Iter 1: mem = 3 | n = 3 //Returns: 6Thursday, July 5, 12
  138. 138. Pluck var stooges = [ Iterates over a collection and {name: moe, age: 40} extracts the values for the input key , {name: larry, age: 50} (assumes all elements in the , {name: curly, age: 60} ]; collection are objects/arrays) _.pluck(stooges, name); //Returns ["moe", "larry", "curly"]Thursday, July 5, 12
  139. 139. Max (Min) var stooges = [ Returns the max item in a {name: moe, age: 40} collection. , {name: larry, age: 50} , {name: curly, age: 60} ]; If second argument (iterator) provided, will use to produce the _.max(stooges, function(s){ value to be compared return s.age; }); //Returns {name: curly, age: 60}Thursday, July 5, 12
  140. 140. Keys _.keys({ Returns the keys from a dictionary one: 1, as an array two: 2, three: 3 }); //Returns ["one", "two", "three"]Thursday, July 5, 12
  141. 141. Defaults var iceCream = { Maps a duplicate input dictionary flavor: "chocolate" on top of a predefined “default” }; dictionary _.defaults(iceCream, { flavor: "vanilla" , sprinkles: "lots" }); //Returns {flavor : "chocolate", sprinkles : "lots"}Thursday, July 5, 12
  142. 142. Chaining var stooges = [ When chain is initiated, method {name : curly, age : 25}, return a self-reference back to {name : moe, age : 21}, underscore but with the value {name : larry, age : 23} ]; attached [similar to opening with _(val)]. var youngest = _.chain(stooges) .sortBy(function(s){ The chain continues until the value return s.age; is extracted using .value() }) .map(function(s){ return s.name + is + s.age; }) .first() .value(); //Returns "moe is 21"Thursday, July 5, 12
  143. 143. Chain: FUN! _(request.params).chain() chain: begins a chain .map(function(v, k) { return [k,v]; map: takes dictionary and maps to }) .sortBy(function(a) { a nested array [[key, val], return a[0]; [key, val], ..] }) .reduce(function(s, v){ sortBy: sorts array returned by map s[v[0]] = v[1]; return s; by key (first element) }, {}) .value(); reduce: reforms an object using the nested list, [0] as key and [1] as value value: spits out the value an ends the chainThursday, July 5, 12
  144. 144. Backbone.jsThursday, July 5, 12
  145. 145. 2010 Backbone.js DocumentCloudThursday, July 5, 12
  146. 146. Backbone.js • Micro application framework • Relies on jQuery/Zepto and Underscore.js • Provides Views, Models, Collections, and Router • If standard REST, default sync will work out of boxThursday, July 5, 12
  147. 147. Model • Fires events on value changes • Must use model.get() and model.set()Thursday, July 5, 12
  148. 148. Collection • Collection of models • Can be enforced • Fires events on add, remove, reset, etcThursday, July 5, 12
  149. 149. View • Creates own DOM object (or utilizes existing one) • Easy event delegation/undelegationThursday, July 5, 12
  150. 150. Router • Hash/History Router • History management abstraction providedThursday, July 5, 12
  151. 151. Require.jsThursday, July 5, 12
  152. 152. 2009 Require.js James BurkeThursday, July 5, 12
  153. 153. Require.js • Implements AMD • Asynchronous Module Definition • Dependency ManagementThursday, July 5, 12
  154. 154. r.js • Optimizer, Compiler • Concatenates dependencies into single file, optionally runs closure/uglifyjs/etcThursday, July 5, 12
  155. 155. Other Libraries Of NoteThursday, July 5, 12
  156. 156. Compilers/Compressors • UglifyJS • http://marijnhaverbeke.nl/uglifyjs • JSmin: • http://www.crockford.com/javascript/jsmin.html • YUI Compressor • http://developer.yahoo.com/yui/compressor/ http://marijnhaverbeke.nl/uglifyjsThursday, July 5, 12
  157. 157. Lawnchair • HTML5 localstorage abstraction • Good suite of storage adapaters • DOM, webkit-sqlite, etc http://brian.io/lawnchairThursday, July 5, 12
  158. 158. Moment.js • Date/Time library • Finally! Almost as easy as DateTime and strtotime() http://momentjs.com/Thursday, July 5, 12
  159. 159. Enyo • Application Framework • Developed for the HP/Palm TouchPad • Now open-source • Designed for nested views and complex, finger-based UI http://enyojs.com/Thursday, July 5, 12
  160. 160. And Many More! http://microjs.com/Thursday, July 5, 12
  161. 161. https://joind.in/6503 http://bit.ly/js-ruby-watThursday, July 5, 12

×