SlideShare a Scribd company logo
1 of 155
Download to read offline
JavaScript Bootcamp
  Alexei White - Nitobi
A bit about me
-Development:
      -Ruby/Rails, PHP, Coldfusion, Some
      ASP.NET, C++ back in the day, Turbo
      Pascal, etc, etc
-Design
-Enterprise Ajax
-Recent Projects:
      -CompleteUI Component Suite
      -Nintendo
      -RobotReplay
      -SayZu
About Nitobi
• Rich Internet Application
development.

• Off-the-shelf Ajax UI
components

• Cross Platform
      •Java
      •ASP.NET
      •PHP
      •Coldfusion
      •Classic ASP
      •Ruby on Rails
• Develop practical
Bootcamp Goals     understanding of ECMAScript

                 • Actual coding

                 • Not too deep, not too shallow

                 • Remove mystery behind Rich
                   Internet Applications

                 • Expose the trouble spots
Today’s Format
•   Part 1 (Basics)                          •   Part 3 (More Advanced)
     – Lexical Structure                          – Object Oriented Programming
     – Datatypes                                  – Ajax (XHR)
     – Variables                                  – DOM Events
     – Operators, Expressions & Statements        – Exercise 3

     – 10 minute break

•   Part 2 (More Advanced)
     – Debugging
     – Basic DOM
     – Exercise 1
     – Threading
     – JavaScript & DHTML
     – Exercise 2

     – 10 minute break
JavaScript Gotcha’s


JavaScript Gotcha’s

• These slides will highlight
  – Some browser-specific difficulty
  – General wierdness
  – Something else
IDE’s - PC              I recomm
                                end
                                      - MAC
•   Aptana Studio                     •   Textmate
     – Integrated Debugging (IE/FF)        • project support
     – Library Support                     • syntax highlighting
          • AIR, Rails, PHP, etc           • snippets
     – SVN Support                    •   Aptana
•   Visual Studio                     •   JSEclipse
     – Integrated debugging           •   Text Editor’s
     – Great Project Support
     – Intellisense
•   JSEclipse
•   Text Editor
     – Notepad++, Textedit
•   Dreamweaver
Part 1

The Basics
Essence of JavaScript (1/2)

• JavaScript != Java
• JavaScript != Simple
Essence of JavaScript (2/2)

•   ECMAScript
•   Dynamic
•   Client-side
•   Prototype based
                         Obj.x = 10;
•   Associative arrays   Obj[“x”] = 10;

•   Weakly typed
Understanding the Client-Server
Boundary
•   JavaScript has no secrets
•   Client is unknown
•   Dynamic – eval()
•   Cross-site communication restricted
The impact of Browsers

• Sandbox implementation errors
• Minor implementation differences
  –   JavaScript
  –   Cascading Style Sheets
  –   Layout
  –   Supported media types
What Can you do in JavaScript?
•   Draw boxes, images, and text
•   Open and close windows
•   Animate on-screen contents
•   Modify the document
•   Communicate with the server
•   Talk to Java, Flash, Silverlight
•   Snoop on the user.. record what they do.
•   Read the mouse/keyboard
What it can’t do (1/2)

•   Can’t open files
•   Write to the file system
                                         y Sa   ndbox”
                                 “Securit
•   Talk directly to hardware
•   Read freely from memory
•   Perform general networking
    – open a socket etc
• Do Ajax across domains
What it can’t do (2/2)

•   Can’t close windows willy-nilly
•   Hide the destination of links
•   Open windows that are too small
•   Set the value of FileUpload fields
•   Rotate graphics
•   Make sound
JAVASCRIPT BASICS
Lexical Structure
Lexical Structure

• All Unicode, all the time
  – UTF-16 can represent most languages
  – String operators respect encoding
• Case Sensitive (Most of the time)
  >>>   var A = 1;   var a = 0;        var a = 0;
  >>>   var a = 2;   WHILE(a <= 2) {   while (a <= 2)
  >>>   a                a+=1;         {
  2                  };                    a+=1;
  >>>   A                              };
  1
Lexical Structure

   • Whitespace ignored
     var a = 2;
     if (a == 2)
         console.log('yep');
     console.log('Carrying on');
     var a = 2; if (a == 2) console.log('yep'); console.log('Carrying on');


   • Optional semicolons
      a = 3                 return          But you probably meant
      b = 4                 true;
                                              return true;
Will be executed as   Will be executed as
      a = 3;                return;
      b = 4;                true;
JavaScript Gotcha’s


Whitespace & Semicolons

• Filesizes reduced by removing whitespace
• Missing semicolons can cause JS errors
                     a = 3
                     b = 4
                 Will be become          y
                                  No Work
                  a = 3 b = 4
Lexical Structure

• Comments
   // This is a single-line comment.
   /* This is also a comment */    // here is another comment

   /*
    * This is a multiline comment
    *
   */


• Literals
   12               //   The number 12
   “hello world”    //   A string of text
   ‘hey now’        //   Another string
   true             //   A boolean value
   /javascript/gi   //   A “regular expression” literal
   Null             //   Absense of an object
Lexical Structure

• Object Literals
   { name: “Alexei”, weight: 160 }   // An object initializer
   [23,345,12,341,2]                 // An array initializer
   [{a:2},{a:56,name:’Buck’},{c:65}] // An array of objects..



• Identifiers (Variables)
   a                                 34fg
   my_variable_name                  .vgf
   v382
   _something
   $
   $fgj
Lexical Structure

• Reserved Words             • Reserved & Special
  break        null                abstract     int
  case         return              boolean      interface
  catch        switch              byte         long
  continue     this                char         native
  default      throw               class        package
                        A biggie
  delete       true                const        private
  do           try                 debugger     protected
  else         typeof              double       public
  false        var                 enum         short
  finally      void                export       static
  for          while               extends      super
  function     with                final        synchronized
  if                               float        throws
  in                               goto         transient
  instanceof                       implements   volatile
  new                              import
Lexical Structure

    • Words to avoid
           arguments            NaN
      ie   Array                Number
A bigg     Boolean              Object
           console              parseFloat
           Date                 parseInt
           decodeURI            RangeError
           decodeURIComponent   ReferenceError
           encodeURI            RegExp
           Error                String
           escape               SyntaxError
           eval                 TypeError
           EvalError            undefined
           Function             unescape
           Infinity             URIError
           isFinite
           isNan
           Math
JAVASCRIPT BASICS
Datatypes
Datatypes

• Number                  • Objects
              Primitive
• String      types         • Arrays
• Boolean                   • Functions
              Referenc
                      e
                            • Dates
                  types
• null                      • RegExp
• undefined                 • Error
Datatypes – Useful Information
•   Numbers
     – All floating point
     – 64 bit (huge)
        • (+/-) 1.7976931348623157x10308
        • Small: 1.474334E-32
     – Hexadecimal Literals
        • 0xff , 0xCAFE911
     – Numeric Constants
        • Infinity, NaN, Number.MAX_VALUE,
            Number.NEGATIVE_INFINITY
Datatypes – Useful Information
•   Strings
     – Modern ECMAScript implementations support Unicode
     – Escape sequences:
          • ‘You’re always saying what can’t be done’
          • u for unicode (eg: u03c0 for π)
     – Concatenation
          • Myname = first_name + ‘ danger ‘ + last_name;
     – Strings are objects
          • Myname.length, Myname.indexOf()
     – Convert numbers to strings
          • Msg = 100 + ‘’; Msg = String(100); Msg = 100.toString();
     – Strings to Numbers
          • Myval = parseInt(“3 people”) // 3
Datatypes – Useful Information
•   Boolean Values
     – Often the result of comparisons (a == 4)
     – Used in control structures:
      if (a == 4)
        b = b + 1;
      else
        b = b – 1;
     –    Type conversions are often automatic
            • Numeric : true == 1, false == 0
         c = true + true       // 2
         d = true + ‘’        // ‘true’
     –    Type conversion is easy
         var x = Boolean(1);             // true
         a = 1;
         var y = !!a;                    // true
Datatypes – functions
function square(x) {   // function is called square, expects 1 argument
  return x*x;          // the function squares its arg and returns result
}                      // function ends here



• Functions can be stored in variables,
  arrays, etc.
• Can define lambda or anonymous
  functions
function square(x) {
  return x*x;                  var square = function(x){ return x*x; }
}                        =
Datatypes – objects

• JavaScript has built-in objects
document.forms             window.innerWidth
document.images            window.scrollY


• Objects are associative arrays
document.forms             document[“forms”]
document.images     =      document[“images”]

• Invoked using new keyword
var a = new Object();                           a.x = 1.1;   a.y = 344;
var now = new Date();
var pattern = new RegExp(“sjavas”, “i”)
Datatypes – objects
• Object literals
  – Comma-separated list of name-value pairs
  – AKA JSON (JavaScript Object Notation)
var vertex = { x:3.2, y:13.2, z:64.3 };
var user = {
    quot;fullNamequot;: quot;John Smithquot;,
    quot;addressquot;: {
        quot;streetAddressquot;: quot;21 2nd Streetquot;,
        quot;cityquot;: quot;New Yorkquot;,
        quot;postalCodequot;: 10021
    },
    quot;phoneNumbersquot;: [
        quot;212 732-1234quot;,
        quot;646 123-4567quot;
    ]
}
Datatypes – objects

• Object conversion: Does an object exist?
if (myObj) {
  // Do something
}




• Objects as strings
a = {b:34,t:4}
b = a + “”          // “[object Object]”
Datatypes - arrays

• A collection of values, like an object
• Can contain any type of JS data
var a = new Array(1.1, “something”, true, {x:43,y:34});

var b = new Array();
b[0] = 1.1;
b[1] = “something”;
b[2] = true;
b[3] = {x:43,y:34};

var c = new Array(20);
Datatypes - arrays
 • Array literals
 var a = [1.2, “something”, true, {x:33,y:34}];


 • Sparse arrays
 var a = [1,,,,5];

 • Array length
 a.length

 • Searching
 var array = [2, 5, 9];
 var index = array.indexOf(5); // index is 1
 index = array.indexOf(7); // index is -1
Datatypes – null & undefined
• null
   – Indicates no value
   – No object
   – Converts to false in Boolean context (if (null))
• undefined
   – Not null
   – Used when a variable is declared but has no value
• Comparing the two
   – null == undefined
   – null !== undefined
Datatypes - dates
• Not a fundamental type, but a class of object
• Easily use local or GMT time.
  var now = new Date(); // create an object holding current
                        // date and time
  var xmas = new Date(2007,11,25);

• Date math, and type conversion
  xmas.setFullYear(xmas.getFullYear() + 1);   // Next christmas
  var weekday = xmas.getDay();                // Day of week

  console.log(“Today is: “ + now.toLocaleString());
                   // Convert to string
                                                          More on this
                                                          Later!
Datatypes – regular expressions

• Pattern matching
• Search and replace
 /^NITOBI/
 /[1-9][0-9]*/
 /bnitobib/i

• Use the string method replace
 Mystr.replace(/bnitobib/I, “NITOBI”);   // capitalize all instances
                                           // of NITOBI.
Datatypes – error objects
•   Represents a runtime error
•   Besides the base Error, there are six other core error types in JavaScript
     –   EvalError
     –   RangeError
     –   ReferenceError
     –   SyntaxError
     –   TypeError
     –   URIError
•   Contains the following properties:
                                                          More on this
     –   constructor
                                                          Later!
     –   message                      try {
     –   name                             throw new Error(quot;Whoops!quot;);
     –   prototype                    } catch (e) {
                                          alert(e.name + quot;: quot; + e.message);
                                      }
Comparing Types

• Equality vs Identity
var a =1;
var b = true;
a == true;      // true

a === true;     // false
b === true;     // true
a !== true;     // true


• Inspecting an identifier (typeof)
typeof(a);      // “number”
typeof(b);      // “boolean”
Value vs Reference

• 3 ways to manipulate data values
  – Copy it
  – Pass it as an argument
  – Compare it
• 2 ways to manipulate variables
  – By value
  – By reference
Value vs Reference
// copying by Value
var a = 1;
var b = a;       // copy by value.. Two distinct values now


// passing an argument by Value
function add_to_sum(sum, x) {
  sum = sum + x;          // this only changes the internal
}                         // copy of x

                              Won’t actually do
add_to_sum(a,1);
                              anything


if (b == 1) b = 2;       // b is a distinct numeric value
                         // a is still 1, and b is 2
Value vs Reference
// copying by reference
var xmas = new Date(2007, 11, 25);
var gift_day = xmas;      // both variables refer to the same object

gift_day.setDate(26);       // we’ve now changed both variables

xmas.getDate();             // returns 26 not 25
function add_to_sum(sum,   x) {                 Perman
                                                        ent
         sum[0] = sum[0]   + x;                changes ly
                                                         ‘sum’ in
         sum[1] = sum[1]   + x;                global c
                                                       ontext
         sum[2] = sum[1]   + x;
}
(xmas == gift_day)          // this is true still
                                                                    Note:
var newdate1 = new Date(2007,10,10);                                Strings are
var newdate2 = new Date(2007,10,10);                                compared by
(newdate1 == newdate2)    // this is false                          value
JAVASCRIPT BASICS
Variables
Typing

• JavaScript is weakly typed
  – A variable can hold a value of any type at any
    time
                                 m.
    i = 10;               ro ble
    i = “ten”;     ,n   op
                 OK
Variable Declaration

• Explicit declaration not required
  – Implicit declaration has scope consequences
     var i;        var message = “hello”;
     var sum;      var i = 0, j = 0, k = 43;
     var i, sum;



• Repeated declaration OK too.
     var i = 1;    // 1
     var i = 2;    // 2
Variable Scope

• Global – available everywhere
• Local – available within a function
• Local > Global
  var scope= “global”;

  function checkscope() {
     var scope = “local”;                         Note:
                                                               pe
     console.log(scope);    // prints ‘local’;    No Block Sco
                                                              CH
  }                                               except SWIT
                                                  & WITH
  console.log(scope);       // prints ‘global’;
Variable Scope
var x = 1;


 function f() {



     function g() {




     }

 }
Garbage Collection

• Memory allocated and deallocated
  automatically
• Interpreter detects when allocated
  memory is unreachable
  var s = “hello”;           // allocate some mem
  var u = s.toUpperCase();   // copy the value to a new string
  s = u;                     // “hello” now unreachable and is destroyed
JavaScript Gotcha’s


Explorer Memory Leaks
                  Object A References B



   Object A                               Object B


                  Object B References A




• Circular references can cause memory
  leaks.
JAVASCRIPT BASICS
Operators, Expressions & Statements
Operators
   Operator   Operand type(s)      Operation performed
      .       Object, identifier      Property access
      []        Array, integer          Array index
      !           Boolean          Logical complement
     ==              Any                 Equality
     ===             Any                 Identity
     &&           Booleans             Logical AND
      ||          Booleans              Logical OR
      ?:      Booleans, any, any   Conditional operator
      ,              Any            Multiple evaluation
Assignment with Operation
Operator   Example     Equivalent
+=         a += b      a=a+b
-=         a -= b      a=a–b
*=         a *= b      a=a*b
/=         a /= b      a=a/b
%=         a %= b      a=a%b
<<=        a <<= b     a = a <<b
>>=        a >>= b     a = a >>b
>>>=       a >>>= b    a = a >>> b
&=         a &= b      a=a&b
|=         a |= b      a=a|b
^=         a ^= b      a=a^b
Conditional Operator (?:)

• Ternary operator (three operands)
 greeting = “hello “ + (username != null ? username : “there”);


• is equivalent to..
 greeting = “hello “;
 if (username != null)
          greeting += username;
 else                                           Don’t rely
          greeting += “there”;                             on
                                                a compil
                                                         er for
                                               code
• Fast, and compact.                           optimiza
                                                        tion
Notes about Statements
• Brackets around expressions are required
   if (expression)
            statement

• Single statements do not require curly-braces
   if (expression)             if (expression) {
            statement                   statement
                                        statement
                               }
• Whitespace ignored
   if (expression) statement   else   statement
If / else if

    • Execute multiple pieces of conditional
      code
if (n == 1) {                            if (n == 1) {
         // Execute code block 1                  // block 1
} else if (n == 2) {                     } else {
         // Execute code block 2                  if (n == 2) {
} else if (n == 3) {                                       // block 2
         // Execute block 3                       } else {
} else {                                                   if (n == 3) {
         // if all else fails, do this                              // block 3
}                                                          } else {
                                                                    // do this
                                                           }
                                                  }
                       Equivilent
                                         }
Switch

• Better if you are just checking the same var
  over and over
  switch(n) {
    case 1:                     // start here if n == 1
            // code   block 1
            break;
    case 2:
                                                          Only use
            // code   block 2
                                                          constants in
            break;
                                                          C A SE
    case 3:
                                                          expressions
            // code   block 3
            break;
    default:                    // if all else fails…
            // code   block 4
            break;
  }
while, do/while
var count = 0;
while (count < 10) {
         console.log(count);
         count++;
}

var count = 0;
do {
         console.log(count);
         count++;
} while (count < 10)


                       Will execute at
                       least once
for
                                                     Curly braces {}
for(initialize ; test ; increment)                   are not required
         statement                                   if just one
                                                     statement
for (var count = 0; count < 10; count++)
         console.log(count);

for(variable in object)
         statement
var o = {x:1, y:2, z:3}              Copies the object
var a = new Array();                 “o” to the array
var I = 0;                           “a”
for(a[i++] in o) {}


                                                            Not all
                                                                      s a re
                                                            propertie
                                                                     ble!
                                                            enumera
JavaScript Gotcha’s


Performance Pitfall
                                                       lated
                                              re-calcu
                                                         IME
                                              E VE R Y T
                                                        - !!
• Array.length is expensive                    --SLOW-
  for (var count = 0; count < myarray.length; count++)
           console.log(count);
• better:
  for (var count = 0, mylen = myarray.length; count < mylen; count++)
           console.log(count);

• best:
  for (var count = myarray.length-1; count > 0; count--)
           console.log(count);
labels

• Any statement may be labeled
  myloop:
            while(something != null) {
                     // code block
            }


• Usually just used for loops
• Used for breaking and continuing
break
• Causes the innermost enclosing loop or switch to exit.
  break;

• Can be combined with labels
  outerloop:
    for(var i = 0; i < 10; i++) {
           innerloop:
             for(var j = 0; j < 10; j++) {
                    if (j > 3) break;    // quit innermost loop
                    if (i == 2) break innerloop;
                    if (i == 4) break outerloop;
             }
    }
continue

• Like break.. but just skips to the next
  iteration of the current loop
  for(i = 0; i < data.length; i++) {
           if (data[i] == null)
                    continue;
           total += data[i];
  }




• Can be used with labels
try/catch/finally/throw
• Create an exception
  try {
           43534987yhfh     // clearly an error
  } catch(myerr) {
           console.log(myerr);
                                    always executes
  } finally {
                                    regardless of what
           //code block
                                    happens in catch() or
  }
                                    try()


• Custom exceptions
  try {
           throw(“User entered invalid data..”);
                                                                  hing
                                                              met
  } catch(myerr) {
           console.log(myerr);                            “So
                                                    w rite ned..”
  } finally {                                   Will appe
                                                     h
           //code block                          bad
  }
with

• Code block that modifies the scope chain
  with(frames[1].document.forms[0]) {
           // access form elements directly here. eg:
           name.value = “something”;
           address.value = “someplace”;
           email.value = “me@home.com”;
  }



• Generally avoided.
  – slow
  – some unexpected behaviors (with init’d vars)
; (empty)

• Has no effect.. but can be useful.
var o = {x:1, y:2, z:3}
var a = new Array();
var I = 0;
for(a[i++] in o) ;
Part 2

More Advanced
ADVANCED JAVASCRIPT
Debugging
Firebug
•   Free Firefox plugin (http://www.getfirebug.com)
•   Shows you 2 important things:
     –   What’s going on in your page when it loads
     –   & After it loads
•   Advanced features
•   Code profiling
•   CSS debugging
•   DOM Inspection
•   JavaScript breakpoints and step-through
•   XHR Debugging
•   JSON Object Inspection
•   Integration with Aptana
MS Script Debugger

•   Step over, into
•   Console window
•   Not much else
•   Visual Studio better (if you have it)
IE Developer Toolbar

•   Useful for debugging CSS in IE
•   Lacks many of the features in Firebug
•   Convenient cache clearing
•   Change CSS attributes on the fly
•   Inspect Cache
•   DOM browsing
Firebug Lite

• JavaScript extension for NON-Firefox
  browsers
• Mimics some of the console features of
  Firebug
• Evaluate JavaScript in-line
• Makes cross-browser testing a lot easier.
Drosera - Safari

•   WebKit JS debugger
•   Code stepping
•   DOM Inspection
•   Mac-only
ADVANCED JAVASCRIPT
Basic DOM
JavaScript in the Browser
• JavaScript should be unobtrusive
   – Separation of concerns
   – Keep it away from markup
   – Modularize it
   – Degrade gracefully*                      Sometimes this is real
                                              hard
   <html>
   <head>
   <script type=quot;text/javascriptquot; src=quot;code.js”></script>
   </head>
   <body>

   </body>
   </html>
Window
• window is global context
• literally means the browser window
• global variables can be referred to as window.variable
• Document object is a member
    – Contains a hierarchical representation of document.
• Contains window info
      – Geometry
      – scroll position
    window.innerHeight
    window.innerWidth
JavaScript Gotcha’s

Window Geometry Browser
Differences
Browser             window.innerHeight   document.body.clientHeight   document.documentElement.clientHeight


Opera 9.5+ strict   window               document                     window

Opera 9.5+ quirks   window               window                       document

Opera 7-9.2         window               window                       document
Opera 6             window               window                       N/A
Mozilla strict      window               document                     window
Mozilla quirks      window               window                       document
KHTML               window               document                     document
Safari              window               document                     document
iCab 3              window               document                     document
iCab 2              window               window                       N/A
IE 6+ strict        N/A                  document                     window
IE 5-7 quirks       N/A                  window                       0
IE 4                N/A                  window                       N/A
ICEbrowser          window               window                       document
Tkhtml Hv3          window               window                       document
Netscape 4          window               N/A                          N/A
onload Event Handler
• onload fires after all HTML, CSS, Images, and JS is
  downloaded to the client.
• At this time, all JavaScript functions and objects part of
  the window object have been registered.
   <html>
   <head>
   <script type=quot;text/javascriptquot; src=quot;code.js”></script>
   </head>
   <body onload=“myFunction()”>

   </body>
   </html>
Document Object Model
• Tree-structure document
• elements, attributes, and text
   – text nodes are immutable
Form Objects, fields, etc

• Forms are held in a collection
  var myForm = document.forms[quot;customerFormquot;];
  myForm = document.customerForm;


• Elements accessible as an array or an
  object
  for (var i = 0, j = myForm.length; i < j; i++)
       console.log(myForm[i].value);

  console.log(myForm.myname.value);
Finding HTML elements
• Get reference to an HTML element
• Use window.document object
• getElementById()
   – returns a reference to the first object with the
     specified ID
• getElementsByName()
   – Returns an array of objects with the specified NAME
     attribute
• getElementsByTagName()
   – Returns a collection of objects with the specified type (ie DIV,
     SPAN, TABLE, etc)
innerHTML

•   Change the content of HTML element
•   Read and Write property
•   Cornerstone of AJAX
•   Elements must have opening and closing
    tags: <p></p> <div></div>
    – but not <img />
    document.getElementById(‘myId’).innerHTML = “some new text”;
setAttribute

• Apply HTML attributes with JavaScript
  object.setAttribute(sName, vValue [, iFlags])


  var myEl = document.getElementById('info_area');
  myEl.setAttribute(quot;classquot;, quot;hoverClassquot;);
createElement / appendChild

• Allow you to insert HTML into the DOM
• Faster than adding with innerHTML
  – Text nodes are immutable
  var myDiv = document.createElement('div');
  myDiv.setAttribute(quot;classquot;, quot;hoverClass2quot;);
  var body = document.getElementsByTagName('body')[0];
  body.appendChild(myDiv);
Other ways to create elements
• Four ways to do it
   – node.cloneNode(bool) – creates a copy of a node..
     and depending on the bool.. copies contents too.
   – document.createElement(el) creates a new element
     node
   – document.createTextNode(txt) creates new text
     node
   – el.innerHTML – Create elements in text and add to
     the DOM that way.
                                   Frowned u
                                             pon.. not
                                   always use
                                              ful. Can be
                                   slow.
Adding/Removing Nodes in the
Document
• node.removeChild(oldNode) removes the child oldNode
  from node


• node.appendChild(newNode) adds newNode as a new
  (last) child node to node


• node.insertBefore(newNode, oldNode) inserts newNode
  as a new child node of node before oldNode


• node.replaceChild(newNode, oldNode) replaces the child
  node oldNode of node with newNode
DOM Navigation
•    node.firstChild
      – Get the first element of the child array
      – same as childNodes[0]
•    node.childNodes
      – Returns collection of all nodes belonging to that node.. 1st level
        only.
•    node.parentNode
      – Returns the element that this node belongs to
•    node.nextSibling
      – Returns the next sibling belonging to this elements parent
•    node.previousSibling
      – Returns the earlier sibling belonging to this elements parent
•    chaining:
    myNode.childNodes[0].childNodes[2].parentNode.nextSibling.previousSibling;
JavaScript Gotcha’s


firstChild & Firefox

• Firefox considers text to be nodes
  – when you think about it, this is correct
  – but its not that convenient
  – whitespace matters
                                            <table>
                                            <tr>
    <table><tr><td></td></tr></table>   =   <td></td>
                                            </tr>
                                            </table>
Exercise 1 – DOM Manipulation
• Use JavaScript and the DOM to create this
  document:            Get optional application template at:
                             http://www.nitobi.com/gwt/ex1.zip


                                                              rr y
                                                      Don’t wo
                                                               ling
                                                      about sty
Exercise 1 – Possible Solution
InsertDOM = function() {

          var myDiv = document.createElement('div');
          var myHeading = document.createElement('h2');
          myHeading.innerHTML = quot;Customer Profilequot;;
          var myP1 = document.createElement('p');
          myP1.innerHTML = quot;Jimmy Smithquot;;
          var myDiv2 = document.createElement('div');
          myDiv2.innerHTML = quot;Jimmy is married with 2 kids and likes to Golf. Favorite beer
is Molson Export.quot;;

         // Here we asseble everything into one node
         myDiv.appendChild(myHeading);
         myDiv.appendChild(myP1);
         myDiv.appendChild(myDiv2);

         var body = document.getElementsByTagName('body')[0];
         body.appendChild(myDiv);
}
Modifying Style Attributes

• Get a reference to the style rule
   var myStyle = myElement.style;



• Modify an attribute:
   myStyle.backgroundColor = ‘#ffff00’;   // yellow
DOM Stylesheet (1/2)
•   Lets you step through each rule in each stylesheet
•   Change selectors
•   Read/write styles
•   Add new rules
•   Affect several elements at same time
•   document.styleSheets collection contains all
    – cssRules
    – href
    – other stuff
DOM Stylesheet (2/2)
• To find and change a class
   – loop through all stylesheets
   – look at the selectorText
   – modify your style when you’ve found it

    if (myRules[k].selectorText == '.specialDiv') {
             myRules[k].style.position = 'absolute';
             myRules[k].style.top = '100px';
             myRules[k].style.left = '100px';
    }
JavaScript Gotcha’s


Cross Browser Alert!

• In FF/Safari you look for cssRules
• In IE you look for rules
 var myRules = (mySheets[i].rules || mySheets[i].cssRules);
ADVANCED JAVASCRIPT
Threading
Threading Model

• JavaScript is single-threaded
• Doc parsing stops when scripts are
  embedded
• Browser stops responding to input when
  event handlers are executed
• Its possible to mimic multi-threading
Pseudo-threading in JavaScript

• Use the timer object to trigger events and
  JavaScript processing
  – setTimeout
                                Hypothetical animation
  – setInterval
A Simple Thread

  • Initiate a timer
      myGlobalReference = setTimeout(function() {drawObject(50)}, 50);



  • Do the work
drawObject = function(x) {
         // do some calculation or move an object a few pixels
          myGlobalReference = setTimeout(function() {drawObject(x+1)}, 50);
}



  • Stop the thread
      clearTimeout(myGlobalReference);
ADVANCED JAVASCRIPT
JavaScript & DHTML
CSS for DHTML
• Key to dynamic HTML is modifying CSS with JS

  Attribute(s)   Description
  position       The type of positioning applied to an element
  top,left       The position from the top left corner of the parent
  width,height   Size of the element
  z-index        Stacking order.. the 3rd dimension
  display        Whether or not the element is rendered at all
  visibility     Whether or not the element is visible
  overflow       What to do with overflow content
  opacity        How opaque or translucent an element is.. CSS3 attribute. IE has
                 alternative
The KEY to DHTML

• Absolute positioning
  – element.style.position = ‘absolute’
  – class { position: absolute; }
• Other options:
  – relative positioning – position is adjusted
    relative to its position in the normal flow
  – fixed positioning – relative to the browser
    window.                         NO IE6
Position something with JS

• Get the element
  myElement = document.getElementById(‘myEL’);



• Set positioning (you could and shouldalso
  do this with a class).
  myElement.style.position = ‘absolute’;



• Set coordinates
  myElement.style.left = ‘20px’;
  myElement.style.top = ‘100px’;
Exercise 2 – Animation & Threading

• Animate a box resizing itself from 100px /
  100px to 300 px / 300 px over several
  seconds




                       Get optional application template at:
                       http://www.nitobi.com/gwt/ex2.zip
Exercise 2 – Possible Solution
AnimateDOMWithThread = function() {

         var myDiv = document.createElement('div');
         myDiv.style.backgroundColor = quot;#FFFF00quot;;
         myDiv.style.width = quot;100pxquot;;
         myDiv.style.height = quot;100pxquot;;
         myDiv.innerHTML = quot;Some textquot;;
         var body = document.getElementsByTagName('body')[0];
         body.appendChild(myDiv);
         window.myAnimObj = setTimeout(function() {animateBox(myDiv,100, 100)},
20);
}

animateBox = function(myBox, w, h) {
         myBox.style.width = w + 'px';
                                                               Absolute
         myBox.style.height = h + 'px';                        positioning
         var neww = w+1; var newh = h+1;                       not required
         if ((neww <= 300) || (newh <= 300))
                  window.myAnimObj = setTimeout(function()
{animateBox(myBox,neww,newh)}, 20);
}
Part 3

More Advanced
ADVANCED JAVASCRIPT
Object Oriented Programming
Object Oriented JavaScript
• JavaScript is a prototypal language
• Class-based OO programming can be
  achieved
   Java             JavaScript
   Strongly Typed   Loosely Typed
   Static           Dynamic
   Classical        Prototypical
   Classes          Functions
   Constructors     Functions
   Methods          Functions
Functions are Objects Too

• Important function methods:
  – call(scope, arg1, arg2 …);
  – apply(scope, [arg1, arg2 …]);
  – caller
• Call and apply used to dynamically
  execute a function in arbitrary scope
Using Call

function showLength() {
  alert(this.length);
}

                 “this” refers to the new
                 Array


showLength.call(new Array(10)); // Alerts 10!
First, a review of an object

• This is an object
 Person = function(fn, ln) {}
Public Members

• Use this keyword
 Person = function(fn, ln) {
   this.firstName = fn;
   this.lastName = ln;
 }

 Person.prototype.getFullName = function() {
   return this.firstName + “ “ + this.lastName;
 }

 var a = new Person(“Alex”, “White”);

 console.log(a.firstName)   // “Alex”
Private Members

• Local scope variables.
• Only accessible from within the
  constructor
 Person = function(fn, ln) {
   var firstName = fn;
   var lastName = ln;
   var getFullName = function() {
     return firstName + “ “ + lastName;
   }
 }
Privileged Members

• getFullName creates closure and therefor
  exposes private vars through a getter();
 Person = function(fn, ln) {
   var firstName = fn;
   var lastName = ln;
   this.getFullName = function() {
     return firstName + quot; quot; + lastName;
   }
 }
Classical JavaScript

• A Function() is a constructor
• Can use new keyword to instantiate to
  create new instances (copy).
  Person = function() {
  }

  var john = new Person();


• Use this to add instance methods and
  properties
  Person = function() {
           this.age = 12;
  }
Basic Non-prototypal Class

• Start with a rectangle:
 Rectangle = function(w, h) {
          this.width = w;
          this.height = h;
          this.area = function() {return this.width*this.height;}
 }

• Create an instance:
 var r = New Rectangle(10,20);
 var a = r.area();                 // 200;


• Innefficient, memory hungry, inflexible
Classical JavaScript

• Use “prototype” keyword to define
  instance properties and methods
• Same result different approach
  Rectangle = function(w, h) {
           this.width = w;
           this.height = h;
  }

  Rectangle.prototype.area = function() {
           return this.width*this.height;
  }


   var r = New Rectangle(10,20);
   var a = r.area();                 // 200;
Another Advantage – Change the
class
• Modify the prototype to add functionality
  to all instances of that prototype
  <!-- … -->

  Rectangle.prototype.widthSquared = function() {
           return this.width*this.width;
  }

  // var r = New Rectangle(10,20);   -- OUR OLD Rectangle OBJECT
  var ws = r.widthSquared();                 // 100;
Classical Inheritance

• The simple approach
 PositionedRectangle = function(x,y,w,h) {
          Rectangle.call(this,w,h);

         // Now we store the left and right coords
         this.x = x;
         this.y = y;
 }

 PositionedRectangle.prototype = new Rectangle();
Inheritance – Simple Approach

• Why this might be bad
  – Explicit reference to Rectangle in the
    constructor – brittle                                            ork
                                                        Will still w s
                                                                    ase
     PositionedRectangle = function(x,y,w,h) {          in most c
              Rectangle.call(this,w,h);

             <!-- … -->


  – Constructor assigned to prototype –
    potentially brittle at compile-time if DOM is
    being drawn
     PositionedRectangle.prototype = new Rectangle();
Inheritance Function                                          remove compile-
                                                              time constructor
extend = function(subClass, baseClass) {                      execution
  function inheritance() {};
  inheritance.prototype = baseClass.prototype;
  subClass.prototype = new inheritance();                      base constructor
  subClass.baseConstructor = baseClass;                        pointer
  if (baseClass.base) {
    baseClass.prototype.base = baseClass.base;
  }
                                                                 base method
  subClass.base = baseClass.prototype;
                                                                 pointers
}

Customer = function (firstName, lastName) {
  Customer.baseConstructor.call(this, firstName, lastName);
  this.balance = 0;
}

Customer.prototype.getFullName = function() {
  Customer.base.getFullName.call(this);
}
extend(Customer, Person);
More on the many ways to Inherit

• http://truecode.blogspot.com/2006/08/ob
  ject-oriented-super-class-method.html
• Douglas Crockford – my hero
  – http://www.crockford.com/javascript/inherita
    nce.html
Classical Interfaces - Mixins

• No compilation in JavaScript so interfaces
  are tough
• Need to rely on mutability of JavaScript
  objects or “mixins”
  var customer1 = new Customer();
  var customer2 = new Customer();

  customer1.pay = function(amout) {
    this.balance -= amount;
  }

  customer1.pay();
  customer2.pay(); // ERROR!
Classical Interfaces - Mixins

• Mutate classes at runtime
• Think of the implications for AOP

var customer1 = new Customer();
var customer2 = new Customer();

Customer.prototype.pay = function(amount) {
  this.balance -= amount;
}

customer1.pay();             var f = Customer.oldFunction
customer2.pay();             Customer.oldFunction = function() {
                               f.call(this);
                               somethingElse();
                             }
ADVANCED JAVASCRIPT
Ajax
Ajax Versus
Traditional
XMLHttpRequest

• The core of Ajax
                                              IE 6 and 7
  var xhr = null;
  try {
    xhr = new ActiveXObject(quot;Microsoft.XMLHTTPquot;);
  } catch(e) {
    xhr = new XMLHttpRequest();             Everybody Else
  }

  xhr.open(quot;GETquot;, quot;http://www.example.com/myResourcequot;, false);
  xhr.send(null);
  showResult(xhr);
                                                      Async = false
XHR Factory

• Use Factory pattern to create XHR objects
  in a cross-browser manner
  xhrFactory = {
    create: function() {
      try {
        xhr = new ActiveXObject(quot;Microsoft.XMLHTTPquot;);
      } cstch(e) {
        xhr = new XMLHttpRequest();
      }
      return xhr;
    }
  }
  var xhr = xhrFactory.create();
Synchronous Requests

• Simplest case
• However, JavaScript thread is locked!

var xhr = xhrFactory.create();
xhr.open(quot;GETquot;, “http://www.example.com/resource”, false);
var response = xhr.send(null);

                                               Async = false
Asynchronous Requests

• Use async requests to prevent locking the
  JavaScript thread

xhr.open(quot;GETquot;, “http://www.example.com/resource”, true);
xhr.onreadystatechange = function() {
  if (xhr.readyState == 4) {
    if (xhr.status == 200) {                    Async = true
      //   deal with the response
    }
  }      Regular HTTP status code
}
Request Types

• GET
xhr.open(“GET”, “http://www.example.com/resource”, false);
var response = xhr.send(null);




• POST
xhr.open(“POST”, “http://www.example.com/resource”, false);
var response = xhr.send(“firstName=john&lastName=doe”);
Data Types

• POST data to the server as either XML or
  form encoded data
• Use XHR setRequestHeader() method
XML
xhr.setRequestHeader(quot;Content-Typequot;,quot;text/xmlquot;);



Form data
xhr.setRequestHeader(quot;Content-Typequot;,quot;application/x-www-form-urlencodedquot;);
Response Data

• We can expect the response from the
  server as XML, JSON, HTML or text
xhr.open(“GET”, “http://www.example.com/resource”, false);
var response = xhr.send(null);

alert(response.responseXml); // Should show a [Document] for XML response
alert(response.responseText); // Should show the XML, JSON, or HTML data


                                                                 e
                                                        Make sur
                                                                   e
                                                        you set th
                                                                   type
                                                        response
                                                                  r ver
                                                         on the se
                                                         too!
What Type of Response?
• XML
  – Good for Web Services and XML RPC
  – A bit more work on the client.. browser
    differences
• JSON
  – Easy, fast                           Just yse
                                                  what
                                                   r…..
                                         you prefe
• HTML
  – No rendering logic on client
  – bandwidth considerations
XML Response

• Various ways of dealing with XML data
  – XML DOM – most compatible
  – XPath – fast and easy
  – XSLT – not supported everywhere
 xhr.open(“GET”, “http://www.example.com/resource”, false);
 var response = xhr.send(null);

 var html = “”;
 var customers = response.responseXml.getElementsByTagName(“customer”);
 for (var i=0; i<customers.length; i++) {
   var customer = customers[i];
   html += “<div>”+customer.childNodes[0].nodeValue+”</div>”;
   html += “<div>”+customer.childNodes[1].nodeValue+”</div>”;
 }
 alert(html);
JSON Response

• Need to instantiate the data into
  JavaScript objects
xhr.open(“GET”, “http://www.example.com/resource”, false);
var response = xhr.send(null);

var html = “”;
var customers = eval(“(“+response.responseText+”)”);
// OR eval(“a = “ + response.responseText);
for (var i=0; i<customers.length; i++) {
  var customer = customers[i];
  html += “<div>”+customer.firstName+”</div>”;
  html += “<div>”+customer.lastName+”</div>”;
}
alert(html);
HTML Response

• Take the HTML from the server and put it
  into the web page DOM
xhr.open(“GET”, “http://www.example.com/resource”, false);
var response = xhr.send(null);

var html = response.responseText
alert(html);
Cross-Domain XHR

• Create <script> element dynamically
var script = document.createElement(“script”);
script.src = “http://www.example.com/resource?callback=myCallback”;
document.getElementsByTagName(“head”)[0].appendChild(script);



• Response from server includes JavaScript
  and calls a callback function
                                   Dynamically generated
• Called JSONP or XMLP             function call

var customers = [{firstName:”John”,lastName:”Doe”}]
myCallback(customers);
JavaScript Gotcha’s


Cross-Domain JSONP Security
• There are serious security risks with JSON
  or XMLP
• Also serious risks with JSON in general
    – Return JSON data in comments to prevent
      non XHR access
<!--
[{firstName:”John”,lastName:”Doe”}]
-->
ADVANCED JAVASCRIPT
DOM Events
DOM Events

• Native Event object contains information
  about the event
• Two approaches to defining events:
  – Inline
  – Unobtrusive
• Unobtrusive approach requires cross-
  browser event attachment
Native Events
• Document
   – load, unload, resize, scroll
• Mouse
   – mouseover, mouseout, mouseup, mousedown, click
• Key
   – keydown, keyup, keypress
• Forms
   – focus, blur, change, keydown, keyup, keypress
JavaScript Gotcha’s

onload Event
• Need the page JavaScript to execute as
  soon as possible
• onload waits for all images etc to load
Firefox
if (document.addEventListener)
  document.addEventListener('DOMContentLoaded', init, false);


Internet Explorer
<!--[if IE]><script defer src=quot;ie_onload.jsquot;></script><![endif]-->

The rest
window.onload = init;
Inline Events

• Most simple event attachment

<div onmouseover=“swapColor(event)” onmouseout=“swapColor(event)”></div>




• What about separating our control from
  our view?
DOM Event Decoration

• Attach event handlers to DOM nodes
  through JavaScript
var domNode = document.getElementById(“myNode”);
domNode.onmouseover = highlight;


                     Function pointer

• This can create memory leaks when using
                               Most common way of creating
  anonymous functions          memory leaks in IE

var domNode = document.getElementById(“myNode”);
domNode.onmouseover = function() { domNode.style.color = ‘red’;};
JavaScript Gotcha’s


DOM Event Decoration
W3C - Firefox                                     Captur
                                                        e
var domNode = document.getElementById(“myNode”);
domNode.addEventListener(“mouseover”, hightlight, false);


                                      Function pointer

Internet Explorer
 var domNode = document.getElementById(“myNode”);
 domNode.attachEvent(“onmouseover”, highlight);


                 Prefixed with “on”
JavaScript Gotcha’s


Event Object
Internet Explorer                    W3C                                  document.documentElement.clientHeight


                                                                          clientX / Y returns the event coordinates without the document scroll position
clientX / Y                          clientX / Y, pageX / Y               taken into account, whereas pageX / Y does take
                                                                          scrolling into account.

N/A                                  currentTarget                        The HTML element to which the event handler was attached.

                                                                          Various key event modifiers to check if ctrlKey, shiftKey ctrlKey, shiftKey the
keyCode, altKey, ctrlKey, shiftKey   keyCode, altKey, ctrlKey, shiftKey
                                                                          Shift or Ctrl key are pressed.
                                                                          The HTML element on which the event actually took place. Both properties are
srcElement                           target
                                                                          supported in Opera and Safari.
type                                 type                                 The event type without the “on” prefix.
                                                                          from is used only for mouseover and mouseout events. Both properties are
fromElement / toElement              relatedTarget
                                                                          supported in Opera and Safari
Event Questions

• How do you access the Event object?
• What does “this” refer to in the event
  handler function?
Event Object

• Passed as argument to event handler in
  W3C model and as a global in IE
W3C
function swapColor(evt) {
}


Internet Explorer
function swapColor() {
  var evt = window.event;
}
Handler Execution Scope

• “this” is the element that handled the
  event (W3C) or the window (IE)
W3C
function swapColor(evt) {
  this.style.color = “#FF0000”;
}

Internet Explorer
function swapColor() {
  window.event.srcElement.style.color
}
Cross-Browser Event Façade

      • Make Internet Explorer look like W3C
      eventManager = {}; // Singleton object            Event type “mouseover”, etc

      eventManager.attachEvent = function(elem, type, handler, capture) {
        // Browser checking for IE vs W3C compliant browser
        if (elem.attachEvent) {                             Detects IE
          // Create two expando properties with function references
          elem[‘evt_' + type] = function() {
            handler.call(elem);
          };                                                Sets scope of “this”
          // Attach one of our expando function references to the event
 IE       elem.attachEvent('on'+type, elem[‘evt_' + type]);
          // Set the capture if it was specified
          if (capture) elem.setCapture(true);
        } else if (elem.addEventListener) {
W3C       elem.addEventListener(type, handler, capture);
        }
      }
Event Flow

• Events have two phases
  – Events are first captured and propagate from
    the <body> to the target element
  – Event then bubbles back up from the target
    element to the <body>
• Capture is very different in IE and W3C but
  important nonetheless
Event Flow
           <body>
  Bubble   <div>
Capture

            <a onclick=“handler()”></a>

           </div>

           </body>
Event Creation

• Programmatic event creation

if (window.attachEvent) // Internet Explorer
{
  element.fireEvent('on'+evtName);
}
else
{
  // create and init a new event
  var newEvent = document.createEvent(evtType);
  newEvent.initKeyEvent(evtName, true, true, document.defaultView,
ctrlKey, altKey, shiftKey, metaKey, keyCode, charCode);
  // dispatch new event
  element.dispatchEvent(newEvent);
}
Exercise 3 – OO JavaScript (if time)
• Create the following objects:
   – Person class
       • age                Get optional application template at:
       • name               http://www.nitobi.com/gwt/ex3.zip
       • height
   – Customer class
       • account balance
       • inherits from Person
• Put at least 1 prototype method on each class.
• Create a few customers
Exercise 3 – Possible Solution
Person = function(fname, lname, age) {
        this.firstName = fname;
        this.lastName = lname;
        this.age = age;
}
Person.prototype.getFullName = function() {
        return this.firstName + quot; quot; + this.lastName; }

Customer = function(fname, lname, age, balance) {
        this.balance = balance;
        Person.call(this,fname, lname, age);

}
Customer.prototype = new Person();
Customer.prototype.getBalance = function() {
        return '$' + this.balance;}
setupCustomers = function() {
        var cust1 = new Customer(quot;Johnquot;, quot;Smithquot;, 24, 233.23);
        console.log(cust1.getFullName());
        console.log(cust1.getBalance());

}
Finito

Questions?

More Related Content

What's hot

Groovy Domain Specific Languages - SpringOne2GX 2012
Groovy Domain Specific Languages - SpringOne2GX 2012Groovy Domain Specific Languages - SpringOne2GX 2012
Groovy Domain Specific Languages - SpringOne2GX 2012Guillaume Laforge
 
Mastering java bytecode with ASM - GeeCON 2012
Mastering java bytecode with ASM - GeeCON 2012Mastering java bytecode with ASM - GeeCON 2012
Mastering java bytecode with ASM - GeeCON 2012Anton Arhipov
 
Getting started with Perl XS and Inline::C
Getting started with Perl XS and Inline::CGetting started with Perl XS and Inline::C
Getting started with Perl XS and Inline::Cdaoswald
 
Javascript basics for automation testing
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testingVikas Thange
 
Javascript The Good Parts v2
Javascript The Good Parts v2Javascript The Good Parts v2
Javascript The Good Parts v2Federico Galassi
 
Javascript session 01 - Introduction to Javascript
Javascript session 01 - Introduction to JavascriptJavascript session 01 - Introduction to Javascript
Javascript session 01 - Introduction to JavascriptLivingston Samuel
 
Zero, one, two, Freddy's coming for you
Zero, one, two, Freddy's coming for youZero, one, two, Freddy's coming for you
Zero, one, two, Freddy's coming for youAndrey Karpov
 
JavaOne 2011 - JVM Bytecode for Dummies
JavaOne 2011 - JVM Bytecode for DummiesJavaOne 2011 - JVM Bytecode for Dummies
JavaOne 2011 - JVM Bytecode for DummiesCharles Nutter
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to JavascriptAnjan Banda
 
JavaScript 101
JavaScript 101JavaScript 101
JavaScript 101ygv2000
 
Java 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevJava 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevMattias Karlsson
 
Mastering Java Bytecode - JAX.de 2012
Mastering Java Bytecode - JAX.de 2012Mastering Java Bytecode - JAX.de 2012
Mastering Java Bytecode - JAX.de 2012Anton Arhipov
 
Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014Jaroslaw Palka
 
DSL's with Groovy
DSL's with GroovyDSL's with Groovy
DSL's with Groovypaulbowler
 

What's hot (18)

Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
Groovy Domain Specific Languages - SpringOne2GX 2012
Groovy Domain Specific Languages - SpringOne2GX 2012Groovy Domain Specific Languages - SpringOne2GX 2012
Groovy Domain Specific Languages - SpringOne2GX 2012
 
Mastering java bytecode with ASM - GeeCON 2012
Mastering java bytecode with ASM - GeeCON 2012Mastering java bytecode with ASM - GeeCON 2012
Mastering java bytecode with ASM - GeeCON 2012
 
Getting started with Perl XS and Inline::C
Getting started with Perl XS and Inline::CGetting started with Perl XS and Inline::C
Getting started with Perl XS and Inline::C
 
Javascript basics for automation testing
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testing
 
Javascript The Good Parts v2
Javascript The Good Parts v2Javascript The Good Parts v2
Javascript The Good Parts v2
 
Javascript session 01 - Introduction to Javascript
Javascript session 01 - Introduction to JavascriptJavascript session 01 - Introduction to Javascript
Javascript session 01 - Introduction to Javascript
 
Practical Groovy DSL
Practical Groovy DSLPractical Groovy DSL
Practical Groovy DSL
 
Javascript
JavascriptJavascript
Javascript
 
Zero, one, two, Freddy's coming for you
Zero, one, two, Freddy's coming for youZero, one, two, Freddy's coming for you
Zero, one, two, Freddy's coming for you
 
JavaOne 2011 - JVM Bytecode for Dummies
JavaOne 2011 - JVM Bytecode for DummiesJavaOne 2011 - JVM Bytecode for Dummies
JavaOne 2011 - JVM Bytecode for Dummies
 
A Life of breakpoint
A Life of breakpointA Life of breakpoint
A Life of breakpoint
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
 
JavaScript 101
JavaScript 101JavaScript 101
JavaScript 101
 
Java 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevJava 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from Oredev
 
Mastering Java Bytecode - JAX.de 2012
Mastering Java Bytecode - JAX.de 2012Mastering Java Bytecode - JAX.de 2012
Mastering Java Bytecode - JAX.de 2012
 
Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014
 
DSL's with Groovy
DSL's with GroovyDSL's with Groovy
DSL's with Groovy
 

Viewers also liked

javascript teach
javascript teachjavascript teach
javascript teachguest3732fa
 
Dapiccoli
DapiccoliDapiccoli
Dapiccolidanya
 
Orchestral Bowings Markings And Uses
Orchestral Bowings Markings And UsesOrchestral Bowings Markings And Uses
Orchestral Bowings Markings And Useslmsabol
 
ApresentaçãO Slides Teste
ApresentaçãO Slides TesteApresentaçãO Slides Teste
ApresentaçãO Slides Testeguestd2062d
 
Ochrona Dziecka W Sieci (Przed Niebezpiecznymi TreśCiami)
Ochrona Dziecka W Sieci (Przed Niebezpiecznymi TreśCiami)Ochrona Dziecka W Sieci (Przed Niebezpiecznymi TreśCiami)
Ochrona Dziecka W Sieci (Przed Niebezpiecznymi TreśCiami)guest3b97e2
 
Gta 4 Previews
Gta 4 PreviewsGta 4 Previews
Gta 4 Previewsgtajeu
 
Warm Ups For Strings
Warm Ups For StringsWarm Ups For Strings
Warm Ups For Stringslmsabol
 
La EducacióN En La Sociedad Del Conocimiento
La EducacióN  En La Sociedad Del ConocimientoLa EducacióN  En La Sociedad Del Conocimiento
La EducacióN En La Sociedad Del ConocimientoHugo Muñoz Sandoval
 
Powerpointprueba
PowerpointpruebaPowerpointprueba
Powerpointpruebaguestd86897
 
Barlach, Ernst.
Barlach, Ernst.Barlach, Ernst.
Barlach, Ernst.palmyra
 
artículos (salud, democracia y sociedad)
artículos (salud, democracia y sociedad)artículos (salud, democracia y sociedad)
artículos (salud, democracia y sociedad)laumar
 
Leadinglines
LeadinglinesLeadinglines
Leadinglinesghsphoto
 
gta IV Screenshots
gta IV Screenshotsgta IV Screenshots
gta IV Screenshotsgtajeu
 
Catalyze Webcast - You Me And Pictures With Linda Yaven - 011008
Catalyze Webcast - You Me And Pictures With Linda Yaven - 011008Catalyze Webcast - You Me And Pictures With Linda Yaven - 011008
Catalyze Webcast - You Me And Pictures With Linda Yaven - 011008guestadfdc6
 
Creatividad
CreatividadCreatividad
Creatividadmaguipsi
 
Games%20 Unit[2]
Games%20 Unit[2]Games%20 Unit[2]
Games%20 Unit[2]mclovin
 

Viewers also liked (20)

javascript teach
javascript teachjavascript teach
javascript teach
 
Dapiccoli
DapiccoliDapiccoli
Dapiccoli
 
Orchestral Bowings Markings And Uses
Orchestral Bowings Markings And UsesOrchestral Bowings Markings And Uses
Orchestral Bowings Markings And Uses
 
ApresentaçãO Slides Teste
ApresentaçãO Slides TesteApresentaçãO Slides Teste
ApresentaçãO Slides Teste
 
Ochrona Dziecka W Sieci (Przed Niebezpiecznymi TreśCiami)
Ochrona Dziecka W Sieci (Przed Niebezpiecznymi TreśCiami)Ochrona Dziecka W Sieci (Przed Niebezpiecznymi TreśCiami)
Ochrona Dziecka W Sieci (Przed Niebezpiecznymi TreśCiami)
 
Gta 4 Previews
Gta 4 PreviewsGta 4 Previews
Gta 4 Previews
 
Warm Ups For Strings
Warm Ups For StringsWarm Ups For Strings
Warm Ups For Strings
 
Tutorial Url Amigable EDUCANTABRIA
Tutorial Url Amigable EDUCANTABRIATutorial Url Amigable EDUCANTABRIA
Tutorial Url Amigable EDUCANTABRIA
 
La EducacióN En La Sociedad Del Conocimiento
La EducacióN  En La Sociedad Del ConocimientoLa EducacióN  En La Sociedad Del Conocimiento
La EducacióN En La Sociedad Del Conocimiento
 
Powerpointprueba
PowerpointpruebaPowerpointprueba
Powerpointprueba
 
Barlach, Ernst.
Barlach, Ernst.Barlach, Ernst.
Barlach, Ernst.
 
artículos (salud, democracia y sociedad)
artículos (salud, democracia y sociedad)artículos (salud, democracia y sociedad)
artículos (salud, democracia y sociedad)
 
Leadinglines
LeadinglinesLeadinglines
Leadinglines
 
Pavlov
PavlovPavlov
Pavlov
 
gta IV Screenshots
gta IV Screenshotsgta IV Screenshots
gta IV Screenshots
 
Catalyze Webcast - You Me And Pictures With Linda Yaven - 011008
Catalyze Webcast - You Me And Pictures With Linda Yaven - 011008Catalyze Webcast - You Me And Pictures With Linda Yaven - 011008
Catalyze Webcast - You Me And Pictures With Linda Yaven - 011008
 
Vila Carioca Tijuca
Vila Carioca TijucaVila Carioca Tijuca
Vila Carioca Tijuca
 
Creatividad
CreatividadCreatividad
Creatividad
 
Day
DayDay
Day
 
Games%20 Unit[2]
Games%20 Unit[2]Games%20 Unit[2]
Games%20 Unit[2]
 

Similar to JSBootcamp_White

Ajax Tutorial
Ajax TutorialAjax Tutorial
Ajax Tutorialoscon2007
 
Building a JavaScript Library
Building a JavaScript LibraryBuilding a JavaScript Library
Building a JavaScript Libraryjeresig
 
Efficient JavaScript Development
Efficient JavaScript DevelopmentEfficient JavaScript Development
Efficient JavaScript Developmentwolframkriesing
 
Ola Bini Evolving The Java Platform
Ola Bini Evolving The Java PlatformOla Bini Evolving The Java Platform
Ola Bini Evolving The Java Platformdeimos
 
Ajax and JavaScript Bootcamp
Ajax and JavaScript BootcampAjax and JavaScript Bootcamp
Ajax and JavaScript BootcampAndreCharland
 
Groovy a Scripting Language for Java
Groovy a Scripting Language for JavaGroovy a Scripting Language for Java
Groovy a Scripting Language for JavaCharles Anderson
 
Tamarin And Ecmascript 4
Tamarin And Ecmascript 4Tamarin And Ecmascript 4
Tamarin And Ecmascript 4elliando dias
 
Javascriptbootcamp
JavascriptbootcampJavascriptbootcamp
Javascriptbootcamposcon2007
 
Maintainable JavaScript
Maintainable JavaScriptMaintainable JavaScript
Maintainable JavaScriptNicholas Zakas
 
Quick Intro To JRuby
Quick Intro To JRubyQuick Intro To JRuby
Quick Intro To JRubyFrederic Jean
 
JavaScript 1.5 to 2.0 (TomTom)
JavaScript 1.5 to 2.0 (TomTom)JavaScript 1.5 to 2.0 (TomTom)
JavaScript 1.5 to 2.0 (TomTom)jeresig
 
Scala: functional programming for the imperative mind
Scala: functional programming for the imperative mindScala: functional programming for the imperative mind
Scala: functional programming for the imperative mindSander Mak (@Sander_Mak)
 
Hacking with ruby2ruby
Hacking with ruby2rubyHacking with ruby2ruby
Hacking with ruby2rubyMarc Chung
 
Rapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and RailsRapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and Railselliando dias
 
Real-world polyglot programming on the JVM - Ben Summers (ONEIS)
Real-world polyglot programming on the JVM  - Ben Summers (ONEIS)Real-world polyglot programming on the JVM  - Ben Summers (ONEIS)
Real-world polyglot programming on the JVM - Ben Summers (ONEIS)jaxLondonConference
 
Rubish- A Quixotic Shell
Rubish- A Quixotic ShellRubish- A Quixotic Shell
Rubish- A Quixotic Shellguest3464d2
 

Similar to JSBootcamp_White (20)

Ajax Tutorial
Ajax TutorialAjax Tutorial
Ajax Tutorial
 
Building a JavaScript Library
Building a JavaScript LibraryBuilding a JavaScript Library
Building a JavaScript Library
 
Efficient JavaScript Development
Efficient JavaScript DevelopmentEfficient JavaScript Development
Efficient JavaScript Development
 
Better code in JavaScript
Better code in JavaScriptBetter code in JavaScript
Better code in JavaScript
 
Ola Bini Evolving The Java Platform
Ola Bini Evolving The Java PlatformOla Bini Evolving The Java Platform
Ola Bini Evolving The Java Platform
 
Javascript status 2016
Javascript status 2016Javascript status 2016
Javascript status 2016
 
Ajax and JavaScript Bootcamp
Ajax and JavaScript BootcampAjax and JavaScript Bootcamp
Ajax and JavaScript Bootcamp
 
Groovy a Scripting Language for Java
Groovy a Scripting Language for JavaGroovy a Scripting Language for Java
Groovy a Scripting Language for Java
 
Scala Sjug 09
Scala Sjug 09Scala Sjug 09
Scala Sjug 09
 
Tamarin And Ecmascript 4
Tamarin And Ecmascript 4Tamarin And Ecmascript 4
Tamarin And Ecmascript 4
 
Javascriptbootcamp
JavascriptbootcampJavascriptbootcamp
Javascriptbootcamp
 
Maintainable JavaScript
Maintainable JavaScriptMaintainable JavaScript
Maintainable JavaScript
 
Quick Intro To JRuby
Quick Intro To JRubyQuick Intro To JRuby
Quick Intro To JRuby
 
JavaScript 1.5 to 2.0 (TomTom)
JavaScript 1.5 to 2.0 (TomTom)JavaScript 1.5 to 2.0 (TomTom)
JavaScript 1.5 to 2.0 (TomTom)
 
Scala: functional programming for the imperative mind
Scala: functional programming for the imperative mindScala: functional programming for the imperative mind
Scala: functional programming for the imperative mind
 
Hacking with ruby2ruby
Hacking with ruby2rubyHacking with ruby2ruby
Hacking with ruby2ruby
 
Os Wilhelm
Os WilhelmOs Wilhelm
Os Wilhelm
 
Rapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and RailsRapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and Rails
 
Real-world polyglot programming on the JVM - Ben Summers (ONEIS)
Real-world polyglot programming on the JVM  - Ben Summers (ONEIS)Real-world polyglot programming on the JVM  - Ben Summers (ONEIS)
Real-world polyglot programming on the JVM - Ben Summers (ONEIS)
 
Rubish- A Quixotic Shell
Rubish- A Quixotic ShellRubish- A Quixotic Shell
Rubish- A Quixotic Shell
 

Recently uploaded

Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...BookNet Canada
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sectoritnewsafrica
 
Kuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorialKuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorialJoão Esperancinha
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
A Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxA Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxAna-Maria Mihalceanu
 
Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#Karmanjay Verma
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesManik S Magar
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...itnewsafrica
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Kaya Weers
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxfnnc6jmgwh
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024TopCSSGallery
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
Infrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsInfrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsYoss Cohen
 
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Mark Simos
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 

Recently uploaded (20)

Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector
 
Kuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorialKuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorial
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
A Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxA Glance At The Java Performance Toolbox
A Glance At The Java Performance Toolbox
 
Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
Infrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsInfrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platforms
 
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 

JSBootcamp_White

  • 1. JavaScript Bootcamp Alexei White - Nitobi
  • 2. A bit about me -Development: -Ruby/Rails, PHP, Coldfusion, Some ASP.NET, C++ back in the day, Turbo Pascal, etc, etc -Design -Enterprise Ajax -Recent Projects: -CompleteUI Component Suite -Nintendo -RobotReplay -SayZu
  • 3. About Nitobi • Rich Internet Application development. • Off-the-shelf Ajax UI components • Cross Platform •Java •ASP.NET •PHP •Coldfusion •Classic ASP •Ruby on Rails
  • 4. • Develop practical Bootcamp Goals understanding of ECMAScript • Actual coding • Not too deep, not too shallow • Remove mystery behind Rich Internet Applications • Expose the trouble spots
  • 5. Today’s Format • Part 1 (Basics) • Part 3 (More Advanced) – Lexical Structure – Object Oriented Programming – Datatypes – Ajax (XHR) – Variables – DOM Events – Operators, Expressions & Statements – Exercise 3 – 10 minute break • Part 2 (More Advanced) – Debugging – Basic DOM – Exercise 1 – Threading – JavaScript & DHTML – Exercise 2 – 10 minute break
  • 6. JavaScript Gotcha’s JavaScript Gotcha’s • These slides will highlight – Some browser-specific difficulty – General wierdness – Something else
  • 7. IDE’s - PC I recomm end - MAC • Aptana Studio • Textmate – Integrated Debugging (IE/FF) • project support – Library Support • syntax highlighting • AIR, Rails, PHP, etc • snippets – SVN Support • Aptana • Visual Studio • JSEclipse – Integrated debugging • Text Editor’s – Great Project Support – Intellisense • JSEclipse • Text Editor – Notepad++, Textedit • Dreamweaver
  • 9. Essence of JavaScript (1/2) • JavaScript != Java • JavaScript != Simple
  • 10. Essence of JavaScript (2/2) • ECMAScript • Dynamic • Client-side • Prototype based Obj.x = 10; • Associative arrays Obj[“x”] = 10; • Weakly typed
  • 11. Understanding the Client-Server Boundary • JavaScript has no secrets • Client is unknown • Dynamic – eval() • Cross-site communication restricted
  • 12. The impact of Browsers • Sandbox implementation errors • Minor implementation differences – JavaScript – Cascading Style Sheets – Layout – Supported media types
  • 13. What Can you do in JavaScript? • Draw boxes, images, and text • Open and close windows • Animate on-screen contents • Modify the document • Communicate with the server • Talk to Java, Flash, Silverlight • Snoop on the user.. record what they do. • Read the mouse/keyboard
  • 14. What it can’t do (1/2) • Can’t open files • Write to the file system y Sa ndbox” “Securit • Talk directly to hardware • Read freely from memory • Perform general networking – open a socket etc • Do Ajax across domains
  • 15. What it can’t do (2/2) • Can’t close windows willy-nilly • Hide the destination of links • Open windows that are too small • Set the value of FileUpload fields • Rotate graphics • Make sound
  • 17. Lexical Structure • All Unicode, all the time – UTF-16 can represent most languages – String operators respect encoding • Case Sensitive (Most of the time) >>> var A = 1; var a = 0; var a = 0; >>> var a = 2; WHILE(a <= 2) { while (a <= 2) >>> a a+=1; { 2 }; a+=1; >>> A }; 1
  • 18. Lexical Structure • Whitespace ignored var a = 2; if (a == 2) console.log('yep'); console.log('Carrying on'); var a = 2; if (a == 2) console.log('yep'); console.log('Carrying on'); • Optional semicolons a = 3 return But you probably meant b = 4 true; return true; Will be executed as Will be executed as a = 3; return; b = 4; true;
  • 19. JavaScript Gotcha’s Whitespace & Semicolons • Filesizes reduced by removing whitespace • Missing semicolons can cause JS errors a = 3 b = 4 Will be become y No Work a = 3 b = 4
  • 20. Lexical Structure • Comments // This is a single-line comment. /* This is also a comment */ // here is another comment /* * This is a multiline comment * */ • Literals 12 // The number 12 “hello world” // A string of text ‘hey now’ // Another string true // A boolean value /javascript/gi // A “regular expression” literal Null // Absense of an object
  • 21. Lexical Structure • Object Literals { name: “Alexei”, weight: 160 } // An object initializer [23,345,12,341,2] // An array initializer [{a:2},{a:56,name:’Buck’},{c:65}] // An array of objects.. • Identifiers (Variables) a 34fg my_variable_name .vgf v382 _something $ $fgj
  • 22. Lexical Structure • Reserved Words • Reserved & Special break null abstract int case return boolean interface catch switch byte long continue this char native default throw class package A biggie delete true const private do try debugger protected else typeof double public false var enum short finally void export static for while extends super function with final synchronized if float throws in goto transient instanceof implements volatile new import
  • 23. Lexical Structure • Words to avoid arguments NaN ie Array Number A bigg Boolean Object console parseFloat Date parseInt decodeURI RangeError decodeURIComponent ReferenceError encodeURI RegExp Error String escape SyntaxError eval TypeError EvalError undefined Function unescape Infinity URIError isFinite isNan Math
  • 25. Datatypes • Number • Objects Primitive • String types • Arrays • Boolean • Functions Referenc e • Dates types • null • RegExp • undefined • Error
  • 26. Datatypes – Useful Information • Numbers – All floating point – 64 bit (huge) • (+/-) 1.7976931348623157x10308 • Small: 1.474334E-32 – Hexadecimal Literals • 0xff , 0xCAFE911 – Numeric Constants • Infinity, NaN, Number.MAX_VALUE, Number.NEGATIVE_INFINITY
  • 27. Datatypes – Useful Information • Strings – Modern ECMAScript implementations support Unicode – Escape sequences: • ‘You’re always saying what can’t be done’ • u for unicode (eg: u03c0 for π) – Concatenation • Myname = first_name + ‘ danger ‘ + last_name; – Strings are objects • Myname.length, Myname.indexOf() – Convert numbers to strings • Msg = 100 + ‘’; Msg = String(100); Msg = 100.toString(); – Strings to Numbers • Myval = parseInt(“3 people”) // 3
  • 28. Datatypes – Useful Information • Boolean Values – Often the result of comparisons (a == 4) – Used in control structures: if (a == 4) b = b + 1; else b = b – 1; – Type conversions are often automatic • Numeric : true == 1, false == 0 c = true + true // 2 d = true + ‘’ // ‘true’ – Type conversion is easy var x = Boolean(1); // true a = 1; var y = !!a; // true
  • 29. Datatypes – functions function square(x) { // function is called square, expects 1 argument return x*x; // the function squares its arg and returns result } // function ends here • Functions can be stored in variables, arrays, etc. • Can define lambda or anonymous functions function square(x) { return x*x; var square = function(x){ return x*x; } } =
  • 30. Datatypes – objects • JavaScript has built-in objects document.forms window.innerWidth document.images window.scrollY • Objects are associative arrays document.forms document[“forms”] document.images = document[“images”] • Invoked using new keyword var a = new Object(); a.x = 1.1; a.y = 344; var now = new Date(); var pattern = new RegExp(“sjavas”, “i”)
  • 31. Datatypes – objects • Object literals – Comma-separated list of name-value pairs – AKA JSON (JavaScript Object Notation) var vertex = { x:3.2, y:13.2, z:64.3 }; var user = { quot;fullNamequot;: quot;John Smithquot;, quot;addressquot;: { quot;streetAddressquot;: quot;21 2nd Streetquot;, quot;cityquot;: quot;New Yorkquot;, quot;postalCodequot;: 10021 }, quot;phoneNumbersquot;: [ quot;212 732-1234quot;, quot;646 123-4567quot; ] }
  • 32. Datatypes – objects • Object conversion: Does an object exist? if (myObj) { // Do something } • Objects as strings a = {b:34,t:4} b = a + “” // “[object Object]”
  • 33. Datatypes - arrays • A collection of values, like an object • Can contain any type of JS data var a = new Array(1.1, “something”, true, {x:43,y:34}); var b = new Array(); b[0] = 1.1; b[1] = “something”; b[2] = true; b[3] = {x:43,y:34}; var c = new Array(20);
  • 34. Datatypes - arrays • Array literals var a = [1.2, “something”, true, {x:33,y:34}]; • Sparse arrays var a = [1,,,,5]; • Array length a.length • Searching var array = [2, 5, 9]; var index = array.indexOf(5); // index is 1 index = array.indexOf(7); // index is -1
  • 35. Datatypes – null & undefined • null – Indicates no value – No object – Converts to false in Boolean context (if (null)) • undefined – Not null – Used when a variable is declared but has no value • Comparing the two – null == undefined – null !== undefined
  • 36. Datatypes - dates • Not a fundamental type, but a class of object • Easily use local or GMT time. var now = new Date(); // create an object holding current // date and time var xmas = new Date(2007,11,25); • Date math, and type conversion xmas.setFullYear(xmas.getFullYear() + 1); // Next christmas var weekday = xmas.getDay(); // Day of week console.log(“Today is: “ + now.toLocaleString()); // Convert to string More on this Later!
  • 37. Datatypes – regular expressions • Pattern matching • Search and replace /^NITOBI/ /[1-9][0-9]*/ /bnitobib/i • Use the string method replace Mystr.replace(/bnitobib/I, “NITOBI”); // capitalize all instances // of NITOBI.
  • 38. Datatypes – error objects • Represents a runtime error • Besides the base Error, there are six other core error types in JavaScript – EvalError – RangeError – ReferenceError – SyntaxError – TypeError – URIError • Contains the following properties: More on this – constructor Later! – message try { – name throw new Error(quot;Whoops!quot;); – prototype } catch (e) { alert(e.name + quot;: quot; + e.message); }
  • 39. Comparing Types • Equality vs Identity var a =1; var b = true; a == true; // true a === true; // false b === true; // true a !== true; // true • Inspecting an identifier (typeof) typeof(a); // “number” typeof(b); // “boolean”
  • 40. Value vs Reference • 3 ways to manipulate data values – Copy it – Pass it as an argument – Compare it • 2 ways to manipulate variables – By value – By reference
  • 41. Value vs Reference // copying by Value var a = 1; var b = a; // copy by value.. Two distinct values now // passing an argument by Value function add_to_sum(sum, x) { sum = sum + x; // this only changes the internal } // copy of x Won’t actually do add_to_sum(a,1); anything if (b == 1) b = 2; // b is a distinct numeric value // a is still 1, and b is 2
  • 42. Value vs Reference // copying by reference var xmas = new Date(2007, 11, 25); var gift_day = xmas; // both variables refer to the same object gift_day.setDate(26); // we’ve now changed both variables xmas.getDate(); // returns 26 not 25 function add_to_sum(sum, x) { Perman ent sum[0] = sum[0] + x; changes ly ‘sum’ in sum[1] = sum[1] + x; global c ontext sum[2] = sum[1] + x; } (xmas == gift_day) // this is true still Note: var newdate1 = new Date(2007,10,10); Strings are var newdate2 = new Date(2007,10,10); compared by (newdate1 == newdate2) // this is false value
  • 44. Typing • JavaScript is weakly typed – A variable can hold a value of any type at any time m. i = 10; ro ble i = “ten”; ,n op OK
  • 45. Variable Declaration • Explicit declaration not required – Implicit declaration has scope consequences var i; var message = “hello”; var sum; var i = 0, j = 0, k = 43; var i, sum; • Repeated declaration OK too. var i = 1; // 1 var i = 2; // 2
  • 46. Variable Scope • Global – available everywhere • Local – available within a function • Local > Global var scope= “global”; function checkscope() { var scope = “local”; Note: pe console.log(scope); // prints ‘local’; No Block Sco CH } except SWIT & WITH console.log(scope); // prints ‘global’;
  • 47. Variable Scope var x = 1; function f() { function g() { } }
  • 48. Garbage Collection • Memory allocated and deallocated automatically • Interpreter detects when allocated memory is unreachable var s = “hello”; // allocate some mem var u = s.toUpperCase(); // copy the value to a new string s = u; // “hello” now unreachable and is destroyed
  • 49. JavaScript Gotcha’s Explorer Memory Leaks Object A References B Object A Object B Object B References A • Circular references can cause memory leaks.
  • 51. Operators Operator Operand type(s) Operation performed . Object, identifier Property access [] Array, integer Array index ! Boolean Logical complement == Any Equality === Any Identity && Booleans Logical AND || Booleans Logical OR ?: Booleans, any, any Conditional operator , Any Multiple evaluation
  • 52. Assignment with Operation Operator Example Equivalent += a += b a=a+b -= a -= b a=a–b *= a *= b a=a*b /= a /= b a=a/b %= a %= b a=a%b <<= a <<= b a = a <<b >>= a >>= b a = a >>b >>>= a >>>= b a = a >>> b &= a &= b a=a&b |= a |= b a=a|b ^= a ^= b a=a^b
  • 53. Conditional Operator (?:) • Ternary operator (three operands) greeting = “hello “ + (username != null ? username : “there”); • is equivalent to.. greeting = “hello “; if (username != null) greeting += username; else Don’t rely greeting += “there”; on a compil er for code • Fast, and compact. optimiza tion
  • 54. Notes about Statements • Brackets around expressions are required if (expression) statement • Single statements do not require curly-braces if (expression) if (expression) { statement statement statement } • Whitespace ignored if (expression) statement else statement
  • 55. If / else if • Execute multiple pieces of conditional code if (n == 1) { if (n == 1) { // Execute code block 1 // block 1 } else if (n == 2) { } else { // Execute code block 2 if (n == 2) { } else if (n == 3) { // block 2 // Execute block 3 } else { } else { if (n == 3) { // if all else fails, do this // block 3 } } else { // do this } } Equivilent }
  • 56. Switch • Better if you are just checking the same var over and over switch(n) { case 1: // start here if n == 1 // code block 1 break; case 2: Only use // code block 2 constants in break; C A SE case 3: expressions // code block 3 break; default: // if all else fails… // code block 4 break; }
  • 57. while, do/while var count = 0; while (count < 10) { console.log(count); count++; } var count = 0; do { console.log(count); count++; } while (count < 10) Will execute at least once
  • 58. for Curly braces {} for(initialize ; test ; increment) are not required statement if just one statement for (var count = 0; count < 10; count++) console.log(count); for(variable in object) statement var o = {x:1, y:2, z:3} Copies the object var a = new Array(); “o” to the array var I = 0; “a” for(a[i++] in o) {} Not all s a re propertie ble! enumera
  • 59. JavaScript Gotcha’s Performance Pitfall lated re-calcu IME E VE R Y T - !! • Array.length is expensive --SLOW- for (var count = 0; count < myarray.length; count++) console.log(count); • better: for (var count = 0, mylen = myarray.length; count < mylen; count++) console.log(count); • best: for (var count = myarray.length-1; count > 0; count--) console.log(count);
  • 60. labels • Any statement may be labeled myloop: while(something != null) { // code block } • Usually just used for loops • Used for breaking and continuing
  • 61. break • Causes the innermost enclosing loop or switch to exit. break; • Can be combined with labels outerloop: for(var i = 0; i < 10; i++) { innerloop: for(var j = 0; j < 10; j++) { if (j > 3) break; // quit innermost loop if (i == 2) break innerloop; if (i == 4) break outerloop; } }
  • 62. continue • Like break.. but just skips to the next iteration of the current loop for(i = 0; i < data.length; i++) { if (data[i] == null) continue; total += data[i]; } • Can be used with labels
  • 63. try/catch/finally/throw • Create an exception try { 43534987yhfh // clearly an error } catch(myerr) { console.log(myerr); always executes } finally { regardless of what //code block happens in catch() or } try() • Custom exceptions try { throw(“User entered invalid data..”); hing met } catch(myerr) { console.log(myerr); “So w rite ned..” } finally { Will appe h //code block bad }
  • 64. with • Code block that modifies the scope chain with(frames[1].document.forms[0]) { // access form elements directly here. eg: name.value = “something”; address.value = “someplace”; email.value = “me@home.com”; } • Generally avoided. – slow – some unexpected behaviors (with init’d vars)
  • 65. ; (empty) • Has no effect.. but can be useful. var o = {x:1, y:2, z:3} var a = new Array(); var I = 0; for(a[i++] in o) ;
  • 68. Firebug • Free Firefox plugin (http://www.getfirebug.com) • Shows you 2 important things: – What’s going on in your page when it loads – & After it loads • Advanced features • Code profiling • CSS debugging • DOM Inspection • JavaScript breakpoints and step-through • XHR Debugging • JSON Object Inspection • Integration with Aptana
  • 69. MS Script Debugger • Step over, into • Console window • Not much else • Visual Studio better (if you have it)
  • 70. IE Developer Toolbar • Useful for debugging CSS in IE • Lacks many of the features in Firebug • Convenient cache clearing • Change CSS attributes on the fly • Inspect Cache • DOM browsing
  • 71. Firebug Lite • JavaScript extension for NON-Firefox browsers • Mimics some of the console features of Firebug • Evaluate JavaScript in-line • Makes cross-browser testing a lot easier.
  • 72. Drosera - Safari • WebKit JS debugger • Code stepping • DOM Inspection • Mac-only
  • 74. JavaScript in the Browser • JavaScript should be unobtrusive – Separation of concerns – Keep it away from markup – Modularize it – Degrade gracefully* Sometimes this is real hard <html> <head> <script type=quot;text/javascriptquot; src=quot;code.js”></script> </head> <body> </body> </html>
  • 75. Window • window is global context • literally means the browser window • global variables can be referred to as window.variable • Document object is a member – Contains a hierarchical representation of document. • Contains window info – Geometry – scroll position window.innerHeight window.innerWidth
  • 76. JavaScript Gotcha’s Window Geometry Browser Differences Browser window.innerHeight document.body.clientHeight document.documentElement.clientHeight Opera 9.5+ strict window document window Opera 9.5+ quirks window window document Opera 7-9.2 window window document Opera 6 window window N/A Mozilla strict window document window Mozilla quirks window window document KHTML window document document Safari window document document iCab 3 window document document iCab 2 window window N/A IE 6+ strict N/A document window IE 5-7 quirks N/A window 0 IE 4 N/A window N/A ICEbrowser window window document Tkhtml Hv3 window window document Netscape 4 window N/A N/A
  • 77. onload Event Handler • onload fires after all HTML, CSS, Images, and JS is downloaded to the client. • At this time, all JavaScript functions and objects part of the window object have been registered. <html> <head> <script type=quot;text/javascriptquot; src=quot;code.js”></script> </head> <body onload=“myFunction()”> </body> </html>
  • 78. Document Object Model • Tree-structure document • elements, attributes, and text – text nodes are immutable
  • 79. Form Objects, fields, etc • Forms are held in a collection var myForm = document.forms[quot;customerFormquot;]; myForm = document.customerForm; • Elements accessible as an array or an object for (var i = 0, j = myForm.length; i < j; i++) console.log(myForm[i].value); console.log(myForm.myname.value);
  • 80. Finding HTML elements • Get reference to an HTML element • Use window.document object • getElementById() – returns a reference to the first object with the specified ID • getElementsByName() – Returns an array of objects with the specified NAME attribute • getElementsByTagName() – Returns a collection of objects with the specified type (ie DIV, SPAN, TABLE, etc)
  • 81. innerHTML • Change the content of HTML element • Read and Write property • Cornerstone of AJAX • Elements must have opening and closing tags: <p></p> <div></div> – but not <img /> document.getElementById(‘myId’).innerHTML = “some new text”;
  • 82. setAttribute • Apply HTML attributes with JavaScript object.setAttribute(sName, vValue [, iFlags]) var myEl = document.getElementById('info_area'); myEl.setAttribute(quot;classquot;, quot;hoverClassquot;);
  • 83. createElement / appendChild • Allow you to insert HTML into the DOM • Faster than adding with innerHTML – Text nodes are immutable var myDiv = document.createElement('div'); myDiv.setAttribute(quot;classquot;, quot;hoverClass2quot;); var body = document.getElementsByTagName('body')[0]; body.appendChild(myDiv);
  • 84. Other ways to create elements • Four ways to do it – node.cloneNode(bool) – creates a copy of a node.. and depending on the bool.. copies contents too. – document.createElement(el) creates a new element node – document.createTextNode(txt) creates new text node – el.innerHTML – Create elements in text and add to the DOM that way. Frowned u pon.. not always use ful. Can be slow.
  • 85. Adding/Removing Nodes in the Document • node.removeChild(oldNode) removes the child oldNode from node • node.appendChild(newNode) adds newNode as a new (last) child node to node • node.insertBefore(newNode, oldNode) inserts newNode as a new child node of node before oldNode • node.replaceChild(newNode, oldNode) replaces the child node oldNode of node with newNode
  • 86. DOM Navigation • node.firstChild – Get the first element of the child array – same as childNodes[0] • node.childNodes – Returns collection of all nodes belonging to that node.. 1st level only. • node.parentNode – Returns the element that this node belongs to • node.nextSibling – Returns the next sibling belonging to this elements parent • node.previousSibling – Returns the earlier sibling belonging to this elements parent • chaining: myNode.childNodes[0].childNodes[2].parentNode.nextSibling.previousSibling;
  • 87. JavaScript Gotcha’s firstChild & Firefox • Firefox considers text to be nodes – when you think about it, this is correct – but its not that convenient – whitespace matters <table> <tr> <table><tr><td></td></tr></table> = <td></td> </tr> </table>
  • 88. Exercise 1 – DOM Manipulation • Use JavaScript and the DOM to create this document: Get optional application template at: http://www.nitobi.com/gwt/ex1.zip rr y Don’t wo ling about sty
  • 89. Exercise 1 – Possible Solution InsertDOM = function() { var myDiv = document.createElement('div'); var myHeading = document.createElement('h2'); myHeading.innerHTML = quot;Customer Profilequot;; var myP1 = document.createElement('p'); myP1.innerHTML = quot;Jimmy Smithquot;; var myDiv2 = document.createElement('div'); myDiv2.innerHTML = quot;Jimmy is married with 2 kids and likes to Golf. Favorite beer is Molson Export.quot;; // Here we asseble everything into one node myDiv.appendChild(myHeading); myDiv.appendChild(myP1); myDiv.appendChild(myDiv2); var body = document.getElementsByTagName('body')[0]; body.appendChild(myDiv); }
  • 90. Modifying Style Attributes • Get a reference to the style rule var myStyle = myElement.style; • Modify an attribute: myStyle.backgroundColor = ‘#ffff00’; // yellow
  • 91. DOM Stylesheet (1/2) • Lets you step through each rule in each stylesheet • Change selectors • Read/write styles • Add new rules • Affect several elements at same time • document.styleSheets collection contains all – cssRules – href – other stuff
  • 92. DOM Stylesheet (2/2) • To find and change a class – loop through all stylesheets – look at the selectorText – modify your style when you’ve found it if (myRules[k].selectorText == '.specialDiv') { myRules[k].style.position = 'absolute'; myRules[k].style.top = '100px'; myRules[k].style.left = '100px'; }
  • 93. JavaScript Gotcha’s Cross Browser Alert! • In FF/Safari you look for cssRules • In IE you look for rules var myRules = (mySheets[i].rules || mySheets[i].cssRules);
  • 95. Threading Model • JavaScript is single-threaded • Doc parsing stops when scripts are embedded • Browser stops responding to input when event handlers are executed • Its possible to mimic multi-threading
  • 96. Pseudo-threading in JavaScript • Use the timer object to trigger events and JavaScript processing – setTimeout Hypothetical animation – setInterval
  • 97. A Simple Thread • Initiate a timer myGlobalReference = setTimeout(function() {drawObject(50)}, 50); • Do the work drawObject = function(x) { // do some calculation or move an object a few pixels myGlobalReference = setTimeout(function() {drawObject(x+1)}, 50); } • Stop the thread clearTimeout(myGlobalReference);
  • 99. CSS for DHTML • Key to dynamic HTML is modifying CSS with JS Attribute(s) Description position The type of positioning applied to an element top,left The position from the top left corner of the parent width,height Size of the element z-index Stacking order.. the 3rd dimension display Whether or not the element is rendered at all visibility Whether or not the element is visible overflow What to do with overflow content opacity How opaque or translucent an element is.. CSS3 attribute. IE has alternative
  • 100. The KEY to DHTML • Absolute positioning – element.style.position = ‘absolute’ – class { position: absolute; } • Other options: – relative positioning – position is adjusted relative to its position in the normal flow – fixed positioning – relative to the browser window. NO IE6
  • 101. Position something with JS • Get the element myElement = document.getElementById(‘myEL’); • Set positioning (you could and shouldalso do this with a class). myElement.style.position = ‘absolute’; • Set coordinates myElement.style.left = ‘20px’; myElement.style.top = ‘100px’;
  • 102. Exercise 2 – Animation & Threading • Animate a box resizing itself from 100px / 100px to 300 px / 300 px over several seconds Get optional application template at: http://www.nitobi.com/gwt/ex2.zip
  • 103. Exercise 2 – Possible Solution AnimateDOMWithThread = function() { var myDiv = document.createElement('div'); myDiv.style.backgroundColor = quot;#FFFF00quot;; myDiv.style.width = quot;100pxquot;; myDiv.style.height = quot;100pxquot;; myDiv.innerHTML = quot;Some textquot;; var body = document.getElementsByTagName('body')[0]; body.appendChild(myDiv); window.myAnimObj = setTimeout(function() {animateBox(myDiv,100, 100)}, 20); } animateBox = function(myBox, w, h) { myBox.style.width = w + 'px'; Absolute myBox.style.height = h + 'px'; positioning var neww = w+1; var newh = h+1; not required if ((neww <= 300) || (newh <= 300)) window.myAnimObj = setTimeout(function() {animateBox(myBox,neww,newh)}, 20); }
  • 106. Object Oriented JavaScript • JavaScript is a prototypal language • Class-based OO programming can be achieved Java JavaScript Strongly Typed Loosely Typed Static Dynamic Classical Prototypical Classes Functions Constructors Functions Methods Functions
  • 107. Functions are Objects Too • Important function methods: – call(scope, arg1, arg2 …); – apply(scope, [arg1, arg2 …]); – caller • Call and apply used to dynamically execute a function in arbitrary scope
  • 108. Using Call function showLength() { alert(this.length); } “this” refers to the new Array showLength.call(new Array(10)); // Alerts 10!
  • 109. First, a review of an object • This is an object Person = function(fn, ln) {}
  • 110. Public Members • Use this keyword Person = function(fn, ln) { this.firstName = fn; this.lastName = ln; } Person.prototype.getFullName = function() { return this.firstName + “ “ + this.lastName; } var a = new Person(“Alex”, “White”); console.log(a.firstName) // “Alex”
  • 111. Private Members • Local scope variables. • Only accessible from within the constructor Person = function(fn, ln) { var firstName = fn; var lastName = ln; var getFullName = function() { return firstName + “ “ + lastName; } }
  • 112. Privileged Members • getFullName creates closure and therefor exposes private vars through a getter(); Person = function(fn, ln) { var firstName = fn; var lastName = ln; this.getFullName = function() { return firstName + quot; quot; + lastName; } }
  • 113. Classical JavaScript • A Function() is a constructor • Can use new keyword to instantiate to create new instances (copy). Person = function() { } var john = new Person(); • Use this to add instance methods and properties Person = function() { this.age = 12; }
  • 114. Basic Non-prototypal Class • Start with a rectangle: Rectangle = function(w, h) { this.width = w; this.height = h; this.area = function() {return this.width*this.height;} } • Create an instance: var r = New Rectangle(10,20); var a = r.area(); // 200; • Innefficient, memory hungry, inflexible
  • 115. Classical JavaScript • Use “prototype” keyword to define instance properties and methods • Same result different approach Rectangle = function(w, h) { this.width = w; this.height = h; } Rectangle.prototype.area = function() { return this.width*this.height; } var r = New Rectangle(10,20); var a = r.area(); // 200;
  • 116. Another Advantage – Change the class • Modify the prototype to add functionality to all instances of that prototype <!-- … --> Rectangle.prototype.widthSquared = function() { return this.width*this.width; } // var r = New Rectangle(10,20); -- OUR OLD Rectangle OBJECT var ws = r.widthSquared(); // 100;
  • 117. Classical Inheritance • The simple approach PositionedRectangle = function(x,y,w,h) { Rectangle.call(this,w,h); // Now we store the left and right coords this.x = x; this.y = y; } PositionedRectangle.prototype = new Rectangle();
  • 118. Inheritance – Simple Approach • Why this might be bad – Explicit reference to Rectangle in the constructor – brittle ork Will still w s ase PositionedRectangle = function(x,y,w,h) { in most c Rectangle.call(this,w,h); <!-- … --> – Constructor assigned to prototype – potentially brittle at compile-time if DOM is being drawn PositionedRectangle.prototype = new Rectangle();
  • 119. Inheritance Function remove compile- time constructor extend = function(subClass, baseClass) { execution function inheritance() {}; inheritance.prototype = baseClass.prototype; subClass.prototype = new inheritance(); base constructor subClass.baseConstructor = baseClass; pointer if (baseClass.base) { baseClass.prototype.base = baseClass.base; } base method subClass.base = baseClass.prototype; pointers } Customer = function (firstName, lastName) { Customer.baseConstructor.call(this, firstName, lastName); this.balance = 0; } Customer.prototype.getFullName = function() { Customer.base.getFullName.call(this); } extend(Customer, Person);
  • 120. More on the many ways to Inherit • http://truecode.blogspot.com/2006/08/ob ject-oriented-super-class-method.html • Douglas Crockford – my hero – http://www.crockford.com/javascript/inherita nce.html
  • 121. Classical Interfaces - Mixins • No compilation in JavaScript so interfaces are tough • Need to rely on mutability of JavaScript objects or “mixins” var customer1 = new Customer(); var customer2 = new Customer(); customer1.pay = function(amout) { this.balance -= amount; } customer1.pay(); customer2.pay(); // ERROR!
  • 122. Classical Interfaces - Mixins • Mutate classes at runtime • Think of the implications for AOP var customer1 = new Customer(); var customer2 = new Customer(); Customer.prototype.pay = function(amount) { this.balance -= amount; } customer1.pay(); var f = Customer.oldFunction customer2.pay(); Customer.oldFunction = function() { f.call(this); somethingElse(); }
  • 125. XMLHttpRequest • The core of Ajax IE 6 and 7 var xhr = null; try { xhr = new ActiveXObject(quot;Microsoft.XMLHTTPquot;); } catch(e) { xhr = new XMLHttpRequest(); Everybody Else } xhr.open(quot;GETquot;, quot;http://www.example.com/myResourcequot;, false); xhr.send(null); showResult(xhr); Async = false
  • 126. XHR Factory • Use Factory pattern to create XHR objects in a cross-browser manner xhrFactory = { create: function() { try { xhr = new ActiveXObject(quot;Microsoft.XMLHTTPquot;); } cstch(e) { xhr = new XMLHttpRequest(); } return xhr; } } var xhr = xhrFactory.create();
  • 127. Synchronous Requests • Simplest case • However, JavaScript thread is locked! var xhr = xhrFactory.create(); xhr.open(quot;GETquot;, “http://www.example.com/resource”, false); var response = xhr.send(null); Async = false
  • 128. Asynchronous Requests • Use async requests to prevent locking the JavaScript thread xhr.open(quot;GETquot;, “http://www.example.com/resource”, true); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { if (xhr.status == 200) { Async = true // deal with the response } } Regular HTTP status code }
  • 129. Request Types • GET xhr.open(“GET”, “http://www.example.com/resource”, false); var response = xhr.send(null); • POST xhr.open(“POST”, “http://www.example.com/resource”, false); var response = xhr.send(“firstName=john&lastName=doe”);
  • 130. Data Types • POST data to the server as either XML or form encoded data • Use XHR setRequestHeader() method XML xhr.setRequestHeader(quot;Content-Typequot;,quot;text/xmlquot;); Form data xhr.setRequestHeader(quot;Content-Typequot;,quot;application/x-www-form-urlencodedquot;);
  • 131. Response Data • We can expect the response from the server as XML, JSON, HTML or text xhr.open(“GET”, “http://www.example.com/resource”, false); var response = xhr.send(null); alert(response.responseXml); // Should show a [Document] for XML response alert(response.responseText); // Should show the XML, JSON, or HTML data e Make sur e you set th type response r ver on the se too!
  • 132. What Type of Response? • XML – Good for Web Services and XML RPC – A bit more work on the client.. browser differences • JSON – Easy, fast Just yse what r….. you prefe • HTML – No rendering logic on client – bandwidth considerations
  • 133. XML Response • Various ways of dealing with XML data – XML DOM – most compatible – XPath – fast and easy – XSLT – not supported everywhere xhr.open(“GET”, “http://www.example.com/resource”, false); var response = xhr.send(null); var html = “”; var customers = response.responseXml.getElementsByTagName(“customer”); for (var i=0; i<customers.length; i++) { var customer = customers[i]; html += “<div>”+customer.childNodes[0].nodeValue+”</div>”; html += “<div>”+customer.childNodes[1].nodeValue+”</div>”; } alert(html);
  • 134. JSON Response • Need to instantiate the data into JavaScript objects xhr.open(“GET”, “http://www.example.com/resource”, false); var response = xhr.send(null); var html = “”; var customers = eval(“(“+response.responseText+”)”); // OR eval(“a = “ + response.responseText); for (var i=0; i<customers.length; i++) { var customer = customers[i]; html += “<div>”+customer.firstName+”</div>”; html += “<div>”+customer.lastName+”</div>”; } alert(html);
  • 135. HTML Response • Take the HTML from the server and put it into the web page DOM xhr.open(“GET”, “http://www.example.com/resource”, false); var response = xhr.send(null); var html = response.responseText alert(html);
  • 136. Cross-Domain XHR • Create <script> element dynamically var script = document.createElement(“script”); script.src = “http://www.example.com/resource?callback=myCallback”; document.getElementsByTagName(“head”)[0].appendChild(script); • Response from server includes JavaScript and calls a callback function Dynamically generated • Called JSONP or XMLP function call var customers = [{firstName:”John”,lastName:”Doe”}] myCallback(customers);
  • 137. JavaScript Gotcha’s Cross-Domain JSONP Security • There are serious security risks with JSON or XMLP • Also serious risks with JSON in general – Return JSON data in comments to prevent non XHR access <!-- [{firstName:”John”,lastName:”Doe”}] -->
  • 139. DOM Events • Native Event object contains information about the event • Two approaches to defining events: – Inline – Unobtrusive • Unobtrusive approach requires cross- browser event attachment
  • 140. Native Events • Document – load, unload, resize, scroll • Mouse – mouseover, mouseout, mouseup, mousedown, click • Key – keydown, keyup, keypress • Forms – focus, blur, change, keydown, keyup, keypress
  • 141. JavaScript Gotcha’s onload Event • Need the page JavaScript to execute as soon as possible • onload waits for all images etc to load Firefox if (document.addEventListener) document.addEventListener('DOMContentLoaded', init, false); Internet Explorer <!--[if IE]><script defer src=quot;ie_onload.jsquot;></script><![endif]--> The rest window.onload = init;
  • 142. Inline Events • Most simple event attachment <div onmouseover=“swapColor(event)” onmouseout=“swapColor(event)”></div> • What about separating our control from our view?
  • 143. DOM Event Decoration • Attach event handlers to DOM nodes through JavaScript var domNode = document.getElementById(“myNode”); domNode.onmouseover = highlight; Function pointer • This can create memory leaks when using Most common way of creating anonymous functions memory leaks in IE var domNode = document.getElementById(“myNode”); domNode.onmouseover = function() { domNode.style.color = ‘red’;};
  • 144. JavaScript Gotcha’s DOM Event Decoration W3C - Firefox Captur e var domNode = document.getElementById(“myNode”); domNode.addEventListener(“mouseover”, hightlight, false); Function pointer Internet Explorer var domNode = document.getElementById(“myNode”); domNode.attachEvent(“onmouseover”, highlight); Prefixed with “on”
  • 145. JavaScript Gotcha’s Event Object Internet Explorer W3C document.documentElement.clientHeight clientX / Y returns the event coordinates without the document scroll position clientX / Y clientX / Y, pageX / Y taken into account, whereas pageX / Y does take scrolling into account. N/A currentTarget The HTML element to which the event handler was attached. Various key event modifiers to check if ctrlKey, shiftKey ctrlKey, shiftKey the keyCode, altKey, ctrlKey, shiftKey keyCode, altKey, ctrlKey, shiftKey Shift or Ctrl key are pressed. The HTML element on which the event actually took place. Both properties are srcElement target supported in Opera and Safari. type type The event type without the “on” prefix. from is used only for mouseover and mouseout events. Both properties are fromElement / toElement relatedTarget supported in Opera and Safari
  • 146. Event Questions • How do you access the Event object? • What does “this” refer to in the event handler function?
  • 147. Event Object • Passed as argument to event handler in W3C model and as a global in IE W3C function swapColor(evt) { } Internet Explorer function swapColor() { var evt = window.event; }
  • 148. Handler Execution Scope • “this” is the element that handled the event (W3C) or the window (IE) W3C function swapColor(evt) { this.style.color = “#FF0000”; } Internet Explorer function swapColor() { window.event.srcElement.style.color }
  • 149. Cross-Browser Event Façade • Make Internet Explorer look like W3C eventManager = {}; // Singleton object Event type “mouseover”, etc eventManager.attachEvent = function(elem, type, handler, capture) { // Browser checking for IE vs W3C compliant browser if (elem.attachEvent) { Detects IE // Create two expando properties with function references elem[‘evt_' + type] = function() { handler.call(elem); }; Sets scope of “this” // Attach one of our expando function references to the event IE elem.attachEvent('on'+type, elem[‘evt_' + type]); // Set the capture if it was specified if (capture) elem.setCapture(true); } else if (elem.addEventListener) { W3C elem.addEventListener(type, handler, capture); } }
  • 150. Event Flow • Events have two phases – Events are first captured and propagate from the <body> to the target element – Event then bubbles back up from the target element to the <body> • Capture is very different in IE and W3C but important nonetheless
  • 151. Event Flow <body> Bubble <div> Capture <a onclick=“handler()”></a> </div> </body>
  • 152. Event Creation • Programmatic event creation if (window.attachEvent) // Internet Explorer { element.fireEvent('on'+evtName); } else { // create and init a new event var newEvent = document.createEvent(evtType); newEvent.initKeyEvent(evtName, true, true, document.defaultView, ctrlKey, altKey, shiftKey, metaKey, keyCode, charCode); // dispatch new event element.dispatchEvent(newEvent); }
  • 153. Exercise 3 – OO JavaScript (if time) • Create the following objects: – Person class • age Get optional application template at: • name http://www.nitobi.com/gwt/ex3.zip • height – Customer class • account balance • inherits from Person • Put at least 1 prototype method on each class. • Create a few customers
  • 154. Exercise 3 – Possible Solution Person = function(fname, lname, age) { this.firstName = fname; this.lastName = lname; this.age = age; } Person.prototype.getFullName = function() { return this.firstName + quot; quot; + this.lastName; } Customer = function(fname, lname, age, balance) { this.balance = balance; Person.call(this,fname, lname, age); } Customer.prototype = new Person(); Customer.prototype.getBalance = function() { return '$' + this.balance;} setupCustomers = function() { var cust1 = new Customer(quot;Johnquot;, quot;Smithquot;, 24, 233.23); console.log(cust1.getFullName()); console.log(cust1.getBalance()); }