SlideShare a Scribd company logo
1 of 155
JavaScript Bootcamp Alexei White - Nitobi
A bit about me ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
About Nitobi ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Bootcamp Goals ,[object Object],[object Object],[object Object],[object Object],[object Object]
Today’s Format ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
JavaScript Gotcha’s ,[object Object],[object Object],[object Object],[object Object]
IDE’s - PC ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],- MAC ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],I recommend
Part 1 The Basics
Essence of JavaScript (1/2) ,[object Object],[object Object]
Essence of JavaScript (2/2) ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Obj.x = 10; Obj[“x”] = 10;
Understanding the Client-Server Boundary ,[object Object],[object Object],[object Object],[object Object]
The impact of Browsers ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
What Can you do in JavaScript? ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
What it can’t do (1/2) ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],“ Security Sandbox”
What it can’t do (2/2) ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
JAVASCRIPT BASICS ,[object Object]
Lexical Structure ,[object Object],[object Object],[object Object],[object Object],>>> var A = 1; >>> var a = 2; >>> a 2 >>> A 1 var a = 0; WHILE(a <= 2) { a+=1; }; var a = 0; while (a <= 2) { a+=1; };
Lexical Structure ,[object Object],[object Object],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'); a = 3 b = 4 Will be executed as a = 3; b = 4; return true; Will be executed as return; true; But you probably meant return true;
Whitespace & Semicolons ,[object Object],[object Object],a = 3 b = 4 Will be become a = 3 b = 4 No Worky
Lexical Structure ,[object Object],[object Object],// This is a single-line comment. /* This is also a comment */  // here is another comment /*  * This is a multiline comment * */ ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Lexical Structure ,[object Object],[object Object],{ 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.. a my_variable_name v382 _something $ $fgj 34fg .vgf
Lexical Structure ,[object Object],[object Object],break case catch continue default delete do else false finally for function if in instanceof new null return switch this throw true try typeof var void while with abstract boolean byte char class const debugger double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile A biggie
Lexical Structure ,[object Object],arguments Array Boolean console Date decodeURI decodeURIComponent encodeURI Error escape eval EvalError Function Infinity isFinite isNan Math NaN Number Object parseFloat parseInt RangeError ReferenceError RegExp String SyntaxError TypeError undefined unescape URIError A biggie
JAVASCRIPT BASICS ,[object Object]
Datatypes ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Primitive types Reference types
Datatypes – Useful Information ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Datatypes – Useful Information ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Datatypes – Useful Information ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],if (a == 4) b = b + 1; else b = b – 1; c = true + true  // 2 d = true + ‘’  // ‘true’ var x = Boolean(1); // true a = 1; var y = !!a; // true
Datatypes – functions ,[object Object],[object Object],function square(x) {  // function is called square, expects 1 argument return x*x;   // the function squares its arg and returns result }   // function ends here function square(x) { return x*x; } var square = function(x){ return x*x; } =
Datatypes – objects ,[object Object],[object Object],[object Object],document.forms document.images window.innerWidth window.scrollY document.forms document.images document[“forms”] document[“images”] = var a = new Object(); var now = new Date(); var pattern = new RegExp( “sjavas ”, “i”) a.x = 1.1;  a.y = 344;
Datatypes – objects ,[object Object],[object Object],[object Object],var vertex = { x:3.2, y:13.2, z:64.3 };  var user = { &quot;fullName&quot;: &quot;John Smith&quot;, &quot;address&quot;: { &quot;streetAddress&quot;: &quot;21 2nd Street&quot;, &quot;city&quot;: &quot;New York&quot;, &quot;postalCode&quot;: 10021 }, &quot;phoneNumbers&quot;: [ &quot;212 732-1234&quot;, &quot;646 123-4567&quot; ] }
Datatypes – objects ,[object Object],[object Object],if (myObj) { // Do something } a = {b:34,t:4} b = a + “” // “[object Object]”
Datatypes - arrays ,[object Object],[object Object],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 ,[object Object],[object Object],[object Object],[object Object],var a = [1.2, “something”, true, {x:33,y:34}]; var a = [1,,,,5]; a.length var array = [2, 5, 9]; var index = array.indexOf(5); // index is 1 index = array.indexOf(7);  // index is -1
Datatypes – null & undefined ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Datatypes - dates ,[object Object],[object Object],[object Object],var now = new Date(); // create an object holding current   // date and time var xmas = new Date(2007,11,25); 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 ,[object Object],[object Object],[object Object],/^NITOBI/ /[1-9][0-9]*/ /nitobi/i Mystr.replace(/nitobi/I, “NITOBI”);  // capitalize all instances  // of NITOBI.
Datatypes – error objects ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],try { throw new Error(&quot;Whoops!&quot;); } catch (e) { alert(e.name + &quot;: &quot; + e.message); } More on this Later!
Comparing Types ,[object Object],[object Object],var a =1; var b = true; a == true; // true a === true; // false b === true; // true a !== true; // true typeof(a); // “number” typeof(b); // “boolean”
Value vs Reference ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
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 add_to_sum(a,1); if (b == 1) b = 2; // b is a distinct numeric value // a is still 1, and b is 2 Won’t actually do anything
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 function add_to_sum(sum, x) { sum[0] = sum[0] + x; sum[1] = sum[1] + x; sum[2] = sum[1] + x; } (xmas == gift_day) // this is true still xmas.getDate(); // returns 26 not 25 var newdate1 = new Date(2007,10,10); var newdate2 = new Date(2007,10,10); (newdate1 == newdate2)  // this is false Permanently changes ‘sum’ in global context Note: Strings are compared by value
JAVASCRIPT BASICS ,[object Object]
Typing ,[object Object],[object Object],i = 10; i = “ten”; OK, no problem.
Variable Declaration ,[object Object],[object Object],[object Object],var i; var sum; var i, sum; var message = “hello”; var i = 0, j = 0, k = 43; var i = 1; // 1 var i = 2; // 2
Variable Scope ,[object Object],[object Object],[object Object],var scope= “global”; function checkscope() { var scope = “local”; console.log(scope); // prints ‘local’; } console.log(scope); // prints ‘global’; Note: No Block Scope except SWITCH & WITH
Variable Scope var x = 1; function f() { } function g() { }
Garbage Collection ,[object Object],[object Object],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
Explorer Memory Leaks ,[object Object],Object A Object B Object A References B Object B References A
JAVASCRIPT BASICS ,[object Object]
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 (?:) ,[object Object],[object Object],[object Object],greeting = “hello “ + (username != null ? username : “there”); greeting = “hello “; if (username != null) greeting += username; else greeting += “there”; Don’t rely on a compiler for code optimization
Notes about Statements ,[object Object],[object Object],[object Object],if ( expression ) statement if ( expression ) statement if ( expression ) { statement statement } if ( expression )  statement  else  statement
If / else if ,[object Object],if (n == 1) { // Execute code block 1 } else if (n == 2) { // Execute code block 2 } else if (n == 3) { // Execute block 3 } else { // if all else fails, do this } if (n == 1) { // block 1 } else { if (n == 2) { // block 2 } else { if (n == 3) { // block 3 } else { // do this } } } Equivilent
Switch ,[object Object],switch(n) { case 1: // start here if n == 1 // code block 1 break; case 2: // code block 2 break; case 3: // code block 3 break; default: // if all else fails… // code block 4 break; } Only use constants in CASE expressions
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 for( initialize  ;  test  ;  increment ) statement for (var count = 0; count < 10; count++) console.log(count); for( variable  in  object ) statement var o = {x:1, y:2, z:3} var a = new Array(); var I = 0; for(a[i++] in o) {} Curly braces {} are not required if just one statement Copies the object “o” to the array “a” Not all properties are enumerable!
Performance Pitfall ,[object Object],[object Object],[object Object],for (var count = 0; count < myarray.length; count++) console.log(count); for (var count = 0, mylen = myarray.length; count < mylen; count++) console.log(count); for (var count = myarray.length-1; count > 0; count--) console.log(count); re-calculated EVERY TIME  --SLOW-- !!
labels ,[object Object],[object Object],[object Object],myloop: while(something != null) { // code block }
break ,[object Object],[object Object],break; 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 ,[object Object],[object Object],for(i = 0; i < data.length; i++) { if (data[i] == null) continue; total += data[i]; }
try/catch/finally/throw ,[object Object],[object Object],try { 43534987yhfh // clearly an error } catch(myerr) { console.log(myerr); } finally { //code block } try { throw(“User entered invalid data..”); } catch(myerr) { console.log(myerr); } finally { //code block } always executes regardless of what happens in catch() or try() Will write “Something bad happened..”
with ,[object Object],[object Object],[object Object],[object Object],with(frames[1].document.forms[0]) { // access form elements directly here. eg: name.value = “something”; address.value = “someplace”; email.value = “me@home.com”; }
; (empty) ,[object Object],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 ,[object Object]
Firebug ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
MS Script Debugger ,[object Object],[object Object],[object Object],[object Object]
IE Developer Toolbar ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Firebug Lite ,[object Object],[object Object],[object Object],[object Object]
Drosera - Safari ,[object Object],[object Object],[object Object],[object Object]
ADVANCED JAVASCRIPT ,[object Object]
JavaScript in the Browser ,[object Object],[object Object],[object Object],[object Object],[object Object],<html> <head> <script type=&quot;text/javascript&quot; src=&quot;code.js”></script> </head> <body> </body> </html> Sometimes this is real hard
Window ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],window.innerHeight window.innerWidth
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 ,[object Object],[object Object],<html> <head> <script type=&quot;text/javascript&quot; src=&quot;code.js”></script> </head> <body  onload=“myFunction()” > </body> </html>
Document Object Model ,[object Object],[object Object],[object Object]
Form Objects, fields, etc ,[object Object],[object Object],var myForm = document.forms[&quot;customerForm&quot;]; myForm = document.customerForm; for (var i = 0, j = myForm.length; i < j; i++) console.log(myForm[i].value); console.log(myForm.myname.value);
Finding HTML elements ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
innerHTML ,[object Object],[object Object],[object Object],[object Object],[object Object],document.getElementById(‘myId’).innerHTML = “some new text”;
setAttribute ,[object Object],object.setAttribute(sName, vValue [, iFlags]) var myEl = document.getElementById('info_area'); myEl.setAttribute(&quot;class&quot;, &quot;hoverClass&quot;);
createElement / appendChild ,[object Object],[object Object],[object Object],var myDiv = document.createElement('div'); myDiv.setAttribute(&quot;class&quot;, &quot;hoverClass2&quot;); var body = document.getElementsByTagName('body')[0]; body.appendChild(myDiv);
Other ways to create elements ,[object Object],[object Object],[object Object],[object Object],[object Object],Frowned upon.. not always useful. Can be slow.
Adding/Removing Nodes in the Document ,[object Object],[object Object],[object Object],[object Object]
DOM Navigation ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],myNode.childNodes[0].childNodes[2].parentNode.nextSibling.previousSibling;
firstChild & Firefox ,[object Object],[object Object],[object Object],[object Object],<table><tr><td></td></tr></table> <table> <tr> <td></td> </tr> </table> =
Exercise 1 – DOM Manipulation ,[object Object],Get optional application template at: http://www.nitobi.com/gwt/ex1.zip Don’t worry about styling
Exercise 1 – Possible Solution InsertDOM = function() { var myDiv = document.createElement('div'); var myHeading = document.createElement('h2'); myHeading.innerHTML = &quot;Customer Profile&quot;; var myP1 = document.createElement('p'); myP1.innerHTML = &quot;Jimmy Smith&quot;; 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 ,[object Object],[object Object],var myStyle = myElement.style; myStyle.backgroundColor = ‘#ffff00’; // yellow
DOM Stylesheet (1/2) ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
DOM Stylesheet (2/2) ,[object Object],[object Object],[object Object],[object Object],if (myRules[k].selectorText == '.specialDiv') { myRules[k].style.position = 'absolute'; myRules[k].style.top = '100px'; myRules[k].style.left = '100px'; }
Cross Browser Alert! ,[object Object],[object Object],var myRules = (mySheets[i].rules || mySheets[i].cssRules);
ADVANCED JAVASCRIPT ,[object Object]
Threading Model ,[object Object],[object Object],[object Object],[object Object]
Pseudo-threading in JavaScript ,[object Object],[object Object],[object Object],Hypothetical animation
[object Object],[object Object],[object Object],A Simple Thread myGlobalReference = setTimeout(function() {drawObject(50)}, 50); drawObject = function(x) { // do some calculation or move an object a few pixels   myGlobalReference  = setTimeout(function() {drawObject(x+1)}, 50); } clearTimeout(myGlobalReference);
ADVANCED JAVASCRIPT ,[object Object]
CSS for DHTML ,[object Object],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 3 rd  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 ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],NO IE6
Position something with JS ,[object Object],[object Object],[object Object],myElement = document.getElementById(‘myEL’); myElement.style.position = ‘absolute’; myElement.style.left = ‘20px’; myElement.style.top = ‘100px’;
Exercise 2 – Animation & Threading ,[object Object],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;#FFFF00&quot;; myDiv.style.width = &quot;100px&quot;; myDiv.style.height = &quot;100px&quot;; myDiv.innerHTML = &quot;Some text&quot;; 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'; myBox.style.height = h + 'px'; var neww = w+1; var newh = h+1; if ((neww <= 300) || (newh <= 300)) window.myAnimObj = setTimeout(function() {animateBox(myBox,neww,newh)}, 20); } Absolute positioning not required
Part 3 More Advanced
ADVANCED JAVASCRIPT ,[object Object]
Object Oriented JavaScript ,[object Object],[object Object],Java JavaScript Strongly Typed Loosely Typed Static Dynamic Classical Prototypical Classes Functions Constructors Functions Methods Functions
Functions are Objects Too ,[object Object],[object Object],[object Object],[object Object],[object Object]
Using Call function showLength() { alert(this.length); } showLength.call(new Array(10)); // Alerts 10! “ this” refers to the new Array
First, a review of an object ,[object Object],Person = function(fn, ln) {}
Public Members ,[object Object],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 ,[object Object],[object Object],Person = function(fn, ln) { var firstName = fn; var lastName = ln; var getFullName = function() { return firstName + “ “ + lastName; } }
Privileged Members ,[object Object],Person = function(fn, ln) { var firstName = fn; var lastName = ln; this.getFullName = function() { return firstName + &quot; &quot; + lastName; } }
Classical JavaScript ,[object Object],[object Object],[object Object],Person = function() { } var john = new Person(); Person = function() { this.age = 12; }
Basic Non-prototypal Class ,[object Object],[object Object],[object Object],Rectangle = function(w, h) { this.width = w; this.height = h; this.area = function() {return this.width*this.height;} } var r = New Rectangle(10,20); var a = r.area();  // 200;
Classical JavaScript ,[object Object],[object Object],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 ,[object Object],<!-- … --> 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 ,[object Object],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 ,[object Object],[object Object],[object Object],PositionedRectangle = function(x,y,w,h) { Rectangle.call(this,w,h); <!-- … --> PositionedRectangle.prototype = new Rectangle(); Will still work in most cases
Inheritance Function extend = function(subClass, baseClass) { function inheritance() {}; inheritance.prototype = baseClass.prototype; subClass.prototype = new inheritance(); subClass.baseConstructor = baseClass; if (baseClass.base) { baseClass.prototype.base = baseClass.base; } subClass.base = baseClass.prototype; } 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); remove compile-time constructor execution base constructor pointer base method pointers
More on the many ways to Inherit ,[object Object],[object Object],[object Object]
Classical Interfaces - Mixins ,[object Object],[object Object],var customer1 = new Customer(); var customer2 = new Customer(); customer1.pay = function(amout) { this.balance -= amount; } customer1.pay(); customer2.pay(); // ERROR!
Classical Interfaces - Mixins ,[object Object],[object Object],var customer1 = new Customer(); var customer2 = new Customer(); Customer.prototype.pay = function(amount) { this.balance -= amount; } customer1.pay(); customer2.pay(); var f = Customer.oldFunction Customer.oldFunction = function() { f.call(this); somethingElse(); }
ADVANCED JAVASCRIPT ,[object Object]
Ajax Versus Traditional
XMLHttpRequest ,[object Object],var xhr = null; try { xhr = new ActiveXObject(&quot;Microsoft.XMLHTTP&quot;); } catch(e) { xhr = new XMLHttpRequest(); } xhr.open(&quot;GET&quot;, &quot;http://www.example.com/myResource&quot;, false); xhr.send(null); showResult(xhr); Async = false IE 6 and 7 Everybody Else
XHR Factory ,[object Object],xhrFactory = { create: function() { try { xhr = new ActiveXObject(&quot;Microsoft.XMLHTTP&quot;); } cstch(e) { xhr = new XMLHttpRequest(); } return xhr; } } var xhr = xhrFactory.create();
Synchronous Requests ,[object Object],[object Object],var xhr = xhrFactory.create(); xhr.open(&quot;GET&quot;, “http://www.example.com/resource”, false); var response = xhr.send(null); Async = false
Asynchronous Requests ,[object Object],xhr.open(&quot;GET&quot;, “http://www.example.com/resource”, true); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { if (xhr.status == 200) { //  deal with the response } } } Async = true Regular HTTP status code
Request Types ,[object Object],[object Object],xhr.open(“GET”, “http://www.example.com/resource”, false); var response = xhr.send(null); xhr.open(“POST”, “http://www.example.com/resource”, false); var response = xhr.send(“firstName=john&lastName=doe”);
Data Types ,[object Object],[object Object],xhr.setRequestHeader(&quot;Content-Type&quot;,&quot;text/xml&quot;); xhr.setRequestHeader(&quot;Content-Type&quot;,&quot;application/x-www-form-urlencoded&quot;); XML Form data
Response Data ,[object Object],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 Make sure you set the response type on the server too!
What Type of Response? ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Just yse what you prefer…..
XML Response ,[object Object],[object Object],[object Object],[object Object],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 ,[object Object],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 ,[object Object],xhr.open(“GET”, “http://www.example.com/resource”, false); var response = xhr.send(null); var html = response.responseText alert(html);
Cross-Domain XHR ,[object Object],[object Object],[object Object],var customers = [{firstName:”John”,lastName:”Doe”}] myCallback(customers); var script = document.createElement(“script”); script.src = “http://www.example.com/resource?callback=myCallback”; document.getElementsByTagName(“head”)[0].appendChild(script); Dynamically generated function call
Cross-Domain JSONP Security ,[object Object],[object Object],[object Object],<!-- [{firstName:”John”,lastName:”Doe”}] -->
ADVANCED JAVASCRIPT ,[object Object]
DOM Events ,[object Object],[object Object],[object Object],[object Object],[object Object]
Native Events ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
onload Event ,[object Object],[object Object],if (document.addEventListener) document.addEventListener('DOMContentLoaded', init, false); <!--[if IE]><script defer src=&quot;ie_onload.js&quot;></script><![endif]--> window.onload = init; Firefox Internet Explorer The rest
Inline Events ,[object Object],[object Object],<div onmouseover=“swapColor(event)” onmouseout=“swapColor(event)”></div>
DOM Event Decoration ,[object Object],[object Object],var domNode = document.getElementById(“myNode”); domNode.onmouseover = highlight; var domNode = document.getElementById(“myNode”); domNode.onmouseover = function() { domNode.style.color = ‘red’;}; Function pointer Most common way of creating memory leaks in IE
DOM Event Decoration var domNode = document.getElementById(“myNode”); domNode.attachEvent(“onmouseover”, highlight); W3C - Firefox var domNode = document.getElementById(“myNode”); domNode.addEventListener(“mouseover”, hightlight, false); Internet Explorer Capture Function pointer Prefixed with “on”
Event Object Internet Explorer W3C document.documentElement.clientHeight clientX / Y clientX / Y, pageX / Y clientX / Y returns the event coordinates without the document scroll position taken into account, whereas pageX / Y does take scrolling into account. N/A currentTarget The HTML element to which the event handler was attached. keyCode, altKey, ctrlKey, shiftKey keyCode, altKey, ctrlKey, shiftKey Various key event modifiers to check if ctrlKey, shiftKey ctrlKey, shiftKey the Shift or Ctrl key are pressed. srcElement target The HTML element on which the event actually took place. Both properties  are supported in Opera and Safari. type type The event type without the “on” prefix. fromElement / toElement relatedTarget from is used only for mouseover and mouseout events. Both properties are supported in Opera and Safari
Event Questions ,[object Object],[object Object]
Event Object ,[object Object],function swapColor(evt) { } W3C function swapColor() { var evt = window.event; } Internet Explorer
Handler Execution Scope ,[object Object],function swapColor(evt) { this.style.color = “#FF0000”; } W3C function swapColor() { window.event.srcElement.style.color } Internet Explorer
Cross-Browser Event Façade ,[object Object],eventManager = {}; // Singleton object eventManager.attachEvent = function(elem, type, handler, capture) { // Browser checking for IE vs W3C compliant browser if (elem.attachEvent) { // Create two expando properties with function references elem[‘evt_' + type] = function() { handler.call(elem); }; // Attach one of our expando function references to the event elem.attachEvent('on'+type, elem[‘evt_' + type]); // Set the capture if it was specified if (capture) elem.setCapture(true); } else if (elem.addEventListener) { elem.addEventListener(type, handler, capture); } } IE W3C Sets scope of “this” Event type “mouseover”, etc Detects IE
Event Flow ,[object Object],[object Object],[object Object],[object Object]
Event Flow <body> <div> </div> <a onclick=“handler()”></a> </body> Bubble Capture
Event Creation ,[object Object],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) ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Get optional application template at: http://www.nitobi.com/gwt/ex3.zip
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;John&quot;, &quot;Smith&quot;, 24, 233.23); console.log(cust1.getFullName()); console.log(cust1.getBalance()); }
Finito Questions?

More Related Content

What's hot

Contracts in-clojure-pete
Contracts in-clojure-peteContracts in-clojure-pete
Contracts in-clojure-petejessitron
 
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript BasicsMindfire Solutions
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basicsmsemenistyi
 
Javascript Journey
Javascript JourneyJavascript Journey
Javascript JourneyWanqiang Ji
 
Prototype Utility Methods(1)
Prototype Utility Methods(1)Prototype Utility Methods(1)
Prototype Utility Methods(1)mussawir20
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptWalid Ashraf
 
Serializing EMF models with Xtext
Serializing EMF models with XtextSerializing EMF models with Xtext
Serializing EMF models with Xtextmeysholdt
 
JavaScript Objects
JavaScript ObjectsJavaScript Objects
JavaScript ObjectsReem Alattas
 
LinkedIn TBC JavaScript 100: Intro
LinkedIn TBC JavaScript 100: IntroLinkedIn TBC JavaScript 100: Intro
LinkedIn TBC JavaScript 100: IntroAdam Crabtree
 
javascript objects
javascript objectsjavascript objects
javascript objectsVijay Kalyan
 
Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)jeffz
 
JavaScript - Chapter 4 - Types and Statements
 JavaScript - Chapter 4 - Types and Statements JavaScript - Chapter 4 - Types and Statements
JavaScript - Chapter 4 - Types and StatementsWebStackAcademy
 
Xtext's new Formatter API
Xtext's new Formatter APIXtext's new Formatter API
Xtext's new Formatter APImeysholdt
 
3.1 javascript objects_DOM
3.1 javascript objects_DOM3.1 javascript objects_DOM
3.1 javascript objects_DOMJalpesh Vasa
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to JavascriptAmit Tyagi
 
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...GeeksLab Odessa
 

What's hot (20)

Contracts in-clojure-pete
Contracts in-clojure-peteContracts in-clojure-pete
Contracts in-clojure-pete
 
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript Basics
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basics
 
Javascript Journey
Javascript JourneyJavascript Journey
Javascript Journey
 
Prototype Utility Methods(1)
Prototype Utility Methods(1)Prototype Utility Methods(1)
Prototype Utility Methods(1)
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
 
Serializing EMF models with Xtext
Serializing EMF models with XtextSerializing EMF models with Xtext
Serializing EMF models with Xtext
 
JavaScript Objects
JavaScript ObjectsJavaScript Objects
JavaScript Objects
 
LinkedIn TBC JavaScript 100: Intro
LinkedIn TBC JavaScript 100: IntroLinkedIn TBC JavaScript 100: Intro
LinkedIn TBC JavaScript 100: Intro
 
Scala Intro
Scala IntroScala Intro
Scala Intro
 
javascript objects
javascript objectsjavascript objects
javascript objects
 
Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)
 
JavaScript - Chapter 4 - Types and Statements
 JavaScript - Chapter 4 - Types and Statements JavaScript - Chapter 4 - Types and Statements
JavaScript - Chapter 4 - Types and Statements
 
Javascript
JavascriptJavascript
Javascript
 
Xtext's new Formatter API
Xtext's new Formatter APIXtext's new Formatter API
Xtext's new Formatter API
 
The Xtext Grammar Language
The Xtext Grammar LanguageThe Xtext Grammar Language
The Xtext Grammar Language
 
3.1 javascript objects_DOM
3.1 javascript objects_DOM3.1 javascript objects_DOM
3.1 javascript objects_DOM
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...
 

Viewers also liked

Phone gap day welcome 2012
Phone gap day welcome 2012Phone gap day welcome 2012
Phone gap day welcome 2012AndreCharland
 
PhoneGap Day EU 2012 Welcome
PhoneGap Day EU 2012 WelcomePhoneGap Day EU 2012 Welcome
PhoneGap Day EU 2012 WelcomeAndreCharland
 
Introduction to AJAX
Introduction to AJAXIntroduction to AJAX
Introduction to AJAXjtedesco5
 
Padres Communication Protocols
Padres Communication ProtocolsPadres Communication Protocols
Padres Communication ProtocolsArwid Bancewicz
 

Viewers also liked (6)

Phone gap day welcome 2012
Phone gap day welcome 2012Phone gap day welcome 2012
Phone gap day welcome 2012
 
PhoneGap Day EU 2012 Welcome
PhoneGap Day EU 2012 WelcomePhoneGap Day EU 2012 Welcome
PhoneGap Day EU 2012 Welcome
 
Topic1 Ovrview
Topic1 OvrviewTopic1 Ovrview
Topic1 Ovrview
 
Introduction to AJAX
Introduction to AJAXIntroduction to AJAX
Introduction to AJAX
 
Padres Communication Protocols
Padres Communication ProtocolsPadres Communication Protocols
Padres Communication Protocols
 
jQuery Introduction
jQuery IntroductionjQuery Introduction
jQuery Introduction
 

Similar to Ajax and JavaScript Bootcamp

Similar to Ajax and JavaScript Bootcamp (20)

"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues
 
JavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft TrainingJavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft Training
 
Java Intro
Java IntroJava Intro
Java Intro
 
Master in javascript
Master in javascriptMaster in javascript
Master in javascript
 
JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & Answers
 
Java script
Java scriptJava script
Java script
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Reversing JavaScript
Reversing JavaScriptReversing JavaScript
Reversing JavaScript
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
Javascript status 2016
Javascript status 2016Javascript status 2016
Javascript status 2016
 
JavaScript for Web Analysts
JavaScript for Web AnalystsJavaScript for Web Analysts
JavaScript for Web Analysts
 
Stuff you didn't know about action script
Stuff you didn't know about action scriptStuff you didn't know about action script
Stuff you didn't know about action script
 
JavaScript Workshop
JavaScript WorkshopJavaScript Workshop
JavaScript Workshop
 
Js types
Js typesJs types
Js types
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of Javascript
 
Java
JavaJava
Java
 
Dynamic Python
Dynamic PythonDynamic Python
Dynamic Python
 
JavaScript.pptx
JavaScript.pptxJavaScript.pptx
JavaScript.pptx
 
Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1
 

More from AndreCharland

Kees and Clair Hut Grand Opening - Spearhead Huts Society
Kees and Clair Hut Grand Opening - Spearhead Huts SocietyKees and Clair Hut Grand Opening - Spearhead Huts Society
Kees and Clair Hut Grand Opening - Spearhead Huts SocietyAndreCharland
 
Spearhead fundraising 2019
Spearhead fundraising 2019Spearhead fundraising 2019
Spearhead fundraising 2019AndreCharland
 
Phone gap Stats & Growth
Phone gap Stats & GrowthPhone gap Stats & Growth
Phone gap Stats & GrowthAndreCharland
 
PhoneGap Build Presentation at Deploy2010
PhoneGap Build Presentation at Deploy2010PhoneGap Build Presentation at Deploy2010
PhoneGap Build Presentation at Deploy2010AndreCharland
 
Calendar Finalto Distribute Small
Calendar Finalto Distribute SmallCalendar Finalto Distribute Small
Calendar Finalto Distribute SmallAndreCharland
 
Rad Boob Club Calendar 2010
Rad Boob Club Calendar 2010Rad Boob Club Calendar 2010
Rad Boob Club Calendar 2010AndreCharland
 
InsideRIA Outlook for 2009
InsideRIA Outlook for 2009InsideRIA Outlook for 2009
InsideRIA Outlook for 2009AndreCharland
 
Ajax in AIR from On AIR Tour Europe
Ajax in AIR from On AIR Tour EuropeAjax in AIR from On AIR Tour Europe
Ajax in AIR from On AIR Tour EuropeAndreCharland
 
Ajax Development With Dreamweaver
Ajax Development With DreamweaverAjax Development With Dreamweaver
Ajax Development With DreamweaverAndreCharland
 
Voices That Matter Ajax Overview
Voices That Matter  Ajax OverviewVoices That Matter  Ajax Overview
Voices That Matter Ajax OverviewAndreCharland
 
Enterprise AIR Development for JavaScript Developers
Enterprise AIR Development for JavaScript DevelopersEnterprise AIR Development for JavaScript Developers
Enterprise AIR Development for JavaScript DevelopersAndreCharland
 
Blogging For Business
Blogging For BusinessBlogging For Business
Blogging For BusinessAndreCharland
 
Web Usability in the Enterprise with Ajax
Web Usability in the Enterprise with AjaxWeb Usability in the Enterprise with Ajax
Web Usability in the Enterprise with AjaxAndreCharland
 
Ajax Usability for AjaxWorld
Ajax Usability for AjaxWorldAjax Usability for AjaxWorld
Ajax Usability for AjaxWorldAndreCharland
 
Using the Tools of Web 2.0 for Marketing
Using the Tools of Web 2.0 for MarketingUsing the Tools of Web 2.0 for Marketing
Using the Tools of Web 2.0 for MarketingAndreCharland
 
GIS Applications on the Web
GIS Applications on the WebGIS Applications on the Web
GIS Applications on the WebAndreCharland
 

More from AndreCharland (17)

Kees and Clair Hut Grand Opening - Spearhead Huts Society
Kees and Clair Hut Grand Opening - Spearhead Huts SocietyKees and Clair Hut Grand Opening - Spearhead Huts Society
Kees and Clair Hut Grand Opening - Spearhead Huts Society
 
Spearhead fundraising 2019
Spearhead fundraising 2019Spearhead fundraising 2019
Spearhead fundraising 2019
 
Phone gap Stats & Growth
Phone gap Stats & GrowthPhone gap Stats & Growth
Phone gap Stats & Growth
 
PhoneGap Build Presentation at Deploy2010
PhoneGap Build Presentation at Deploy2010PhoneGap Build Presentation at Deploy2010
PhoneGap Build Presentation at Deploy2010
 
Calendar Finalto Distribute Small
Calendar Finalto Distribute SmallCalendar Finalto Distribute Small
Calendar Finalto Distribute Small
 
Rad Boob Club Calendar 2010
Rad Boob Club Calendar 2010Rad Boob Club Calendar 2010
Rad Boob Club Calendar 2010
 
InsideRIA Outlook for 2009
InsideRIA Outlook for 2009InsideRIA Outlook for 2009
InsideRIA Outlook for 2009
 
Ajax in AIR from On AIR Tour Europe
Ajax in AIR from On AIR Tour EuropeAjax in AIR from On AIR Tour Europe
Ajax in AIR from On AIR Tour Europe
 
Ajax Development With Dreamweaver
Ajax Development With DreamweaverAjax Development With Dreamweaver
Ajax Development With Dreamweaver
 
Adobe AIR Overview
Adobe AIR OverviewAdobe AIR Overview
Adobe AIR Overview
 
Voices That Matter Ajax Overview
Voices That Matter  Ajax OverviewVoices That Matter  Ajax Overview
Voices That Matter Ajax Overview
 
Enterprise AIR Development for JavaScript Developers
Enterprise AIR Development for JavaScript DevelopersEnterprise AIR Development for JavaScript Developers
Enterprise AIR Development for JavaScript Developers
 
Blogging For Business
Blogging For BusinessBlogging For Business
Blogging For Business
 
Web Usability in the Enterprise with Ajax
Web Usability in the Enterprise with AjaxWeb Usability in the Enterprise with Ajax
Web Usability in the Enterprise with Ajax
 
Ajax Usability for AjaxWorld
Ajax Usability for AjaxWorldAjax Usability for AjaxWorld
Ajax Usability for AjaxWorld
 
Using the Tools of Web 2.0 for Marketing
Using the Tools of Web 2.0 for MarketingUsing the Tools of Web 2.0 for Marketing
Using the Tools of Web 2.0 for Marketing
 
GIS Applications on the Web
GIS Applications on the WebGIS Applications on the Web
GIS Applications on the Web
 

Recently uploaded

SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 

Recently uploaded (20)

SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 

Ajax and JavaScript Bootcamp

  • 1. JavaScript Bootcamp Alexei White - Nitobi
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8. Part 1 The Basics
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 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 add_to_sum(a,1); if (b == 1) b = 2; // b is a distinct numeric value // a is still 1, and b is 2 Won’t actually do anything
  • 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 function add_to_sum(sum, x) { sum[0] = sum[0] + x; sum[1] = sum[1] + x; sum[2] = sum[1] + x; } (xmas == gift_day) // this is true still xmas.getDate(); // returns 26 not 25 var newdate1 = new Date(2007,10,10); var newdate2 = new Date(2007,10,10); (newdate1 == newdate2) // this is false Permanently changes ‘sum’ in global context Note: Strings are compared by value
  • 43.
  • 44.
  • 45.
  • 46.
  • 47. Variable Scope var x = 1; function f() { } function g() { }
  • 48.
  • 49.
  • 50.
  • 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.
  • 54.
  • 55.
  • 56.
  • 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 for( initialize ; test ; increment ) statement for (var count = 0; count < 10; count++) console.log(count); for( variable in object ) statement var o = {x:1, y:2, z:3} var a = new Array(); var I = 0; for(a[i++] in o) {} Curly braces {} are not required if just one statement Copies the object “o” to the array “a” Not all properties are enumerable!
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66. Part 2 More Advanced
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76. 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.
  • 78.
  • 79.
  • 80.
  • 81.
  • 82.
  • 83.
  • 84.
  • 85.
  • 86.
  • 87.
  • 88.
  • 89. Exercise 1 – Possible Solution InsertDOM = function() { var myDiv = document.createElement('div'); var myHeading = document.createElement('h2'); myHeading.innerHTML = &quot;Customer Profile&quot;; var myP1 = document.createElement('p'); myP1.innerHTML = &quot;Jimmy Smith&quot;; 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.
  • 91.
  • 92.
  • 93.
  • 94.
  • 95.
  • 96.
  • 97.
  • 98.
  • 99.
  • 100.
  • 101.
  • 102.
  • 103. Exercise 2 – Possible Solution AnimateDOMWithThread = function() { var myDiv = document.createElement('div'); myDiv.style.backgroundColor = &quot;#FFFF00&quot;; myDiv.style.width = &quot;100px&quot;; myDiv.style.height = &quot;100px&quot;; myDiv.innerHTML = &quot;Some text&quot;; 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'; myBox.style.height = h + 'px'; var neww = w+1; var newh = h+1; if ((neww <= 300) || (newh <= 300)) window.myAnimObj = setTimeout(function() {animateBox(myBox,neww,newh)}, 20); } Absolute positioning not required
  • 104. Part 3 More Advanced
  • 105.
  • 106.
  • 107.
  • 108. Using Call function showLength() { alert(this.length); } showLength.call(new Array(10)); // Alerts 10! “ this” refers to the new Array
  • 109.
  • 110.
  • 111.
  • 112.
  • 113.
  • 114.
  • 115.
  • 116.
  • 117.
  • 118.
  • 119. Inheritance Function extend = function(subClass, baseClass) { function inheritance() {}; inheritance.prototype = baseClass.prototype; subClass.prototype = new inheritance(); subClass.baseConstructor = baseClass; if (baseClass.base) { baseClass.prototype.base = baseClass.base; } subClass.base = baseClass.prototype; } 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); remove compile-time constructor execution base constructor pointer base method pointers
  • 120.
  • 121.
  • 122.
  • 123.
  • 125.
  • 126.
  • 127.
  • 128.
  • 129.
  • 130.
  • 131.
  • 132.
  • 133.
  • 134.
  • 135.
  • 136.
  • 137.
  • 138.
  • 139.
  • 140.
  • 141.
  • 142.
  • 143.
  • 144. DOM Event Decoration var domNode = document.getElementById(“myNode”); domNode.attachEvent(“onmouseover”, highlight); W3C - Firefox var domNode = document.getElementById(“myNode”); domNode.addEventListener(“mouseover”, hightlight, false); Internet Explorer Capture Function pointer Prefixed with “on”
  • 145. Event Object Internet Explorer W3C document.documentElement.clientHeight clientX / Y clientX / Y, pageX / Y clientX / Y returns the event coordinates without the document scroll position taken into account, whereas pageX / Y does take scrolling into account. N/A currentTarget The HTML element to which the event handler was attached. keyCode, altKey, ctrlKey, shiftKey keyCode, altKey, ctrlKey, shiftKey Various key event modifiers to check if ctrlKey, shiftKey ctrlKey, shiftKey the Shift or Ctrl key are pressed. srcElement target The HTML element on which the event actually took place. Both properties are supported in Opera and Safari. type type The event type without the “on” prefix. fromElement / toElement relatedTarget from is used only for mouseover and mouseout events. Both properties are supported in Opera and Safari
  • 146.
  • 147.
  • 148.
  • 149.
  • 150.
  • 151. Event Flow <body> <div> </div> <a onclick=“handler()”></a> </body> Bubble Capture
  • 152.
  • 153.
  • 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;John&quot;, &quot;Smith&quot;, 24, 233.23); console.log(cust1.getFullName()); console.log(cust1.getBalance()); }