hebiin87's picture
From hebiin87 rss RSS  subscribe Subscribe

javascript teach 

 

 
 
Tags:  domain  search 
Views:  309
Downloads:  1
Published:  June 10, 2010
 
0
download

Share plick with friends Share
save to favorite
Report Abuse Report Abuse
 
Related Plicks
No related plicks found
 
More from this user
The Critical Need to Secure the Web in Your Company

The Critical Need to Secure the Web in Your Company

From: hebiin87
Views: 252
Comments: 0

UFI Operations Focus Meeting - Paris 2010 - Raul Sanchez

UFI Operations Focus Meeting - Paris 2010 - Raul Sanchez

From: hebiin87
Views: 451
Comments: 0

Vinton Cerf Birth Of The Internet

Vinton Cerf Birth Of The Internet

From: hebiin87
Views: 925
Comments: 0

Thanksgiving 17

Thanksgiving 17

From: hebiin87
Views: 366
Comments: 0

Basic Types of Information Systems

Basic Types of Information Systems

From: hebiin87
Views: 55
Comments: 0

Acer Aod250 1694 10.1 Inch White Netbook   Up To 8 Hours Of Battery Life (Windows 7 Starter)

Acer Aod250 1694 10.1 Inch White Netbook Up To 8 Hours Of Battery Life (Windows 7 Starter)

From: hebiin87
Views: 234
Comments: 0

See all 
 
 
 URL:          AddThis Social Bookmark Button
Embed Thin Player: (fits in most blogs)
Embed Full Player :
 
 

Name

Email (will NOT be shown to other users)

 

 
 
Comments: (watch)
 
 
Notes:
 
Slide 1: JavaScript Bootcamp Alexei White - Nitobi
Slide 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
Slide 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
Slide 4: Bootcamp Goals • Develop practical understanding of ECMAScript • Actual coding • Not too deep, not too shallow • Remove mystery behind Rich Internet Applications • Expose the trouble spots
Slide 5: Today’s Format • Part 1 (Basics) – Lexical Structure – Datatypes – Variables – Operators, Expressions & Statements – 10 minute break • Part 2 (More Advanced) – Debugging – Basic DOM – Exercise 1 – Threading – JavaScript & DHTML – Exercise 2 – 10 minute break • Part 3 (More Advanced) – Object Oriented Programming – Ajax (XHR) – DOM Events – Exercise 3
Slide 6: JavaScript Gotcha’s JavaScript Gotcha’s • These slides will highlight – Some browser-specific difficulty – General wierdness – Something else
Slide 7: IDE’s - PC • • • • • Aptana Studio – Integrated Debugging (IE/FF) – Library Support • AIR, Rails, PHP, etc – SVN Support Visual Studio – Integrated debugging – Great Project Support – Intellisense JSEclipse Text Editor – Notepad++, Textedit Dreamweaver end I recomm - MAC • Textmate • project support • syntax highlighting • snippets Aptana JSEclipse Text Editor’s • • •
Slide 8: Part 1 The Basics
Slide 9: Essence of JavaScript (1/2) • JavaScript != Java • JavaScript != Simple
Slide 10: Essence of JavaScript (2/2) • • • • • • ECMAScript Dynamic Client-side Prototype based Associative arrays Weakly typed Obj.x = 10; Obj[“x”] = 10;
Slide 11: Understanding the Client-Server Boundary • • • • JavaScript has no secrets Client is unknown Dynamic – eval() Cross-site communication restricted
Slide 12: The impact of Browsers • Sandbox implementation errors • Minor implementation differences – – – – JavaScript Cascading Style Sheets Layout Supported media types
Slide 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
Slide 14: What it can’t do (1/2) • • • • • Can’t open files Write to the file system Talk directly to hardware Read freely from memory Perform general networking – open a socket etc y Sa “Securit ndbox” • Do Ajax across domains
Slide 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
Slide 16: JAVASCRIPT BASICS Lexical Structure
Slide 17: Lexical Structure • All Unicode, all the time – UTF-16 can represent most languages – String operators respect encoding • Case Sensitive (Most of the time) >>> >>> >>> 2 >>> 1 var A = 1; var a = 2; a A var a = 0; WHILE(a <= 2) { a+=1; }; var a = 0; while (a <= 2) { a+=1; };
Slide 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 b=4 Will be executed as a = 3; b = 4; return true; Will be executed as return; true; But you probably meant return true;
Slide 19: JavaScript Gotcha’s Whitespace & Semicolons • Filesizes reduced by removing whitespace • Missing semicolons can cause JS errors a=3 b=4 Will be become a=3b=4 y No Work
Slide 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 “hello world” ‘hey now’ true /javascript/gi Null // // // // // // The number 12 A string of text Another string A boolean value A “regular expression” literal Absense of an object
Slide 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 my_variable_name v382 _something $ $fgj 34fg .vgf
Slide 22: Lexical Structure • Reserved Words 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 • Reserved & Special 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
Slide 23: Lexical Structure • Words to avoid ie A bigg 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
Slide 24: JAVASCRIPT BASICS Datatypes
Slide 25: Datatypes • Number • String • Boolean • null • undefined Primitive types Referenc e types • Objects • Arrays • Functions • Dates • RegExp • Error
Slide 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
Slide 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
Slide 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 d = true + ‘’ // 2 // ‘true’ – Type conversion is easy var x = Boolean(1); a = 1; var y = !!a; // true // true
Slide 29: Datatypes – functions function square(x) { return x*x; } // function is called square, expects 1 argument // 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; }
Slide 30: Datatypes – objects • JavaScript has built-in objects document.forms document.images window.innerWidth window.scrollY • Objects are associative arrays document.forms document.images = document[“forms”] document[“images”] • Invoked using new keyword var a = new Object(); var now = new Date(); var pattern = new RegExp(“\\sjava\\s”, “i”) a.x = 1.1; a.y = 344;
Slide 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 = { "fullName": "John Smith", "address": { "streetAddress": "21 2nd Street", "city": "New York", "postalCode": 10021 }, "phoneNumbers": [ "212 732-1234", "646 123-4567" ] }
Slide 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]”
Slide 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);
Slide 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
Slide 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
Slide 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); var weekday = xmas.getDay(); // Next christmas // Day of week console.log(“Today is: “ + now.toLocaleString()); // Convert to string More on this Later!
Slide 37: Datatypes – regular expressions • Pattern matching • Search and replace /^NITOBI/ /[1-9][0-9]*/ /\bnitobi\b/i • Use the string method replace Mystr.replace(/\bnitobi\b/I, “NITOBI”); // capitalize all instances // of NITOBI.
Slide 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 constructor message name prototype More on this Later! • Contains the following properties: – – – – try { throw new Error("Whoops!"); } catch (e) { alert(e.name + ": " + e.message); }
Slide 39: Comparing Types • Equality vs Identity var a =1; var b = true; a == true; a === true; b === true; a !== true; // true // false // true // true • Inspecting an identifier (typeof) typeof(a); typeof(b); // “number” // “boolean”
Slide 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
Slide 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); Won’t actually do anything if (b == 1) b = 2; // b is a distinct numeric value // a is still 1, and b is 2
Slide 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); xmas.getDate(); function add_to_sum(sum, sum[0] = sum[0] sum[1] = sum[1] sum[2] = sum[1] } (xmas == gift_day) // we’ve now changed both variables // returns 26 not 25 x) { + x; + x; + x; Perman ent changes ly ‘sum’ in global c ontext // this is true still Note: Strings are compared by value var newdate1 = new Date(2007,10,10); var newdate2 = new Date(2007,10,10); (newdate1 == newdate2) // this is false
Slide 43: JAVASCRIPT BASICS Variables
Slide 44: Typing • JavaScript is weakly typed – A variable can hold a value of any type at any time i = 10; i = “ten”; ,n OK m. ble ro op
Slide 45: Variable Declaration • Explicit declaration not required – Implicit declaration has scope consequences var i; var sum; var i, sum; var message = “hello”; var i = 0, j = 0, k = 43; • Repeated declaration OK too. var i = 1; var i = 2; // 1 // 2
Slide 46: Variable Scope • Global – available everywhere • Local – available within a function • Local > Global var scope= “global”; function checkscope() { var scope = “local”; console.log(scope); } console.log(scope); Note: pe No Block Sco CH except SWIT & WITH // prints ‘local’; // prints ‘global’;
Slide 47: Variable Scope var x = 1; function f() { function g() { } }
Slide 48: Garbage Collection • Memory allocated and deallocated automatically • Interpreter detects when allocated memory is unreachable var s = “hello”; var u = s.toUpperCase(); s = u; // allocate some mem // copy the value to a new string // “hello” now unreachable and is destroyed
Slide 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.
Slide 50: JAVASCRIPT BASICS Operators, Expressions & Statements
Slide 51: Operators Operator . [] ! == === && || ?: , Operand type(s) Object, identifier Array, integer Boolean Any Any Booleans Booleans Booleans, any, any Any Operation performed Property access Array index Logical complement Equality Identity Logical AND Logical OR Conditional operator Multiple evaluation
Slide 52: Assignment with Operation Operator += -= *= /= %= <<= >>= >>>= &= |= ^= Example a += b a -= b a *= b a /= b a %= b a <<= b a >>= b a >>>= b a &= b a |= b a ^= b Equivalent a=a+b a=a–b a=a*b a=a/b a=a%b a = a <<b a = a >>b a = a >>> b a=a&b a=a|b a=a^b
Slide 53: Conditional Operator (?:) • Ternary operator (three operands) greeting = “hello “ + (username != null ? username : “there”); • is equivalent to.. greeting = “hello “; if (username != null) greeting += username; else greeting += “there”; Don’t rely on a compil er for code optimiza tion • Fast, and compact.
Slide 54: Notes about Statements • Brackets around expressions are required if (expression) statement • Single statements do not require curly-braces if (expression) statement if (expression) { statement statement } • Whitespace ignored if (expression) statement else statement
Slide 55: If / else if • Execute multiple pieces of conditional code 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
Slide 56: Switch • Better if you are just checking the same var over and over switch(n) { case 1: // code break; case 2: // code break; case 3: // code break; default: // code break; } // start here if n == 1 block 1 Only use constants in C A SE expressions block 2 block 3 // if all else fails… block 4
Slide 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
Slide 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) {} Copies the object “o” to the array “a” Curly braces {} are not required if just one statement Not all s a re propertie ble! enumera
Slide 59: JavaScript Gotcha’s Performance Pitfall • Array.length is expensive • better: for (var count = 0, mylen = myarray.length; count < mylen; count++) console.log(count); lated re-calcu IME E VE R Y T - !! --SLOW- for (var count = 0; count < myarray.length; count++) console.log(count); • best: for (var count = myarray.length-1; count > 0; count--) console.log(count);
Slide 60: labels • Any statement may be labeled myloop: while(something != null) { // code block } • Usually just used for loops • Used for breaking and continuing
Slide 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; } }
Slide 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
Slide 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 } catch(myerr) { met “So console.log(myerr); rite ned..” w } finally { Will appe h //code block bad }
Slide 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)
Slide 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) ;
Slide 66: Part 2 More Advanced
Slide 67: ADVANCED JAVASCRIPT Debugging
Slide 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
Slide 69: MS Script Debugger • • • • Step over, into Console window Not much else Visual Studio better (if you have it)
Slide 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
Slide 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.
Slide 72: Drosera - Safari • • • • WebKit JS debugger Code stepping DOM Inspection Mac-only
Slide 73: ADVANCED JAVASCRIPT Basic DOM
Slide 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="text/javascript" src="code.js”></script> </head> <body> </body> </html>
Slide 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
Slide 76: JavaScript Gotcha’s Window Geometry Browser Differences Browser window.innerHeight document.body.clientHeight document.documentElement.clientHeight Opera 9.5+ strict Opera 9.5+ quirks Opera 7-9.2 Opera 6 Mozilla strict Mozilla quirks KHTML Safari iCab 3 iCab 2 IE 6+ strict IE 5-7 quirks IE 4 ICEbrowser Tkhtml Hv3 Netscape 4 window window window window window window window window window window N/A N/A N/A window window window document window window window document window document document document window document window window window window N/A window document document N/A window document document document document N/A window 0 N/A document document N/A
Slide 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="text/javascript" src="code.js”></script> </head> <body onload=“myFunction()”> </body> </html>
Slide 78: Document Object Model • Tree-structure document • elements, attributes, and text – text nodes are immutable
Slide 79: Form Objects, fields, etc • Forms are held in a collection var myForm = document.forms["customerForm"]; 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);
Slide 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)
Slide 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”;
Slide 82: setAttribute • Apply HTML attributes with JavaScript object.setAttribute(sName, vValue [, iFlags]) var myEl = document.getElementById('info_area'); myEl.setAttribute("class", "hoverClass");
Slide 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("class", "hoverClass2"); var body = document.getElementsByTagName('body')[0]; body.appendChild(myDiv);
Slide 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.
Slide 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
Slide 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;
Slide 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><td></td></tr></table> = <table> <tr> <td></td> </tr> </table>
Slide 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
Slide 89: Exercise 1 – Possible Solution InsertDOM = function() { var myDiv = document.createElement('div'); var myHeading = document.createElement('h2'); myHeading.innerHTML = "Customer Profile"; var myP1 = document.createElement('p'); myP1.innerHTML = "Jimmy Smith"; var myDiv2 = document.createElement('div'); myDiv2.innerHTML = "Jimmy is married with 2 kids and likes to Golf. Favorite beer is Molson Export."; // 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); }
Slide 90: Modifying Style Attributes • Get a reference to the style rule var myStyle = myElement.style; • Modify an attribute: myStyle.backgroundColor = ‘#ffff00’; // yellow
Slide 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
Slide 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'; }
Slide 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);
Slide 94: ADVANCED JAVASCRIPT Threading
Slide 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
Slide 96: Pseudo-threading in JavaScript • Use the timer object to trigger events and JavaScript processing – setTimeout – setInterval Hypothetical animation
Slide 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);
Slide 98: ADVANCED JAVASCRIPT JavaScript & DHTML
Slide 99: CSS for DHTML • Key to dynamic HTML is modifying CSS with JS Attribute(s) position top,left width,height z-index display visibility overflow opacity Description The type of positioning applied to an element The position from the top left corner of the parent Size of the element Stacking order.. the 3rd dimension Whether or not the element is rendered at all Whether or not the element is visible What to do with overflow content How opaque or translucent an element is.. CSS3 attribute. IE has alternative
Slide 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
Slide 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’;
Slide 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
Slide 103: Exercise 2 – Possible Solution AnimateDOMWithThread = function() { var myDiv = document.createElement('div'); myDiv.style.backgroundColor = "#FFFF00"; myDiv.style.width = "100px"; myDiv.style.height = "100px"; myDiv.innerHTML = "Some text"; 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
Slide 104: Part 3 More Advanced
Slide 105: ADVANCED JAVASCRIPT Object Oriented Programming
Slide 106: Object Oriented JavaScript • JavaScript is a prototypal language • Class-based OO programming can be achieved Java Strongly Typed Static Classical Classes Constructors Methods JavaScript Loosely Typed Dynamic Prototypical Functions Functions Functions
Slide 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
Slide 108: Using Call function showLength() { alert(this.length); } “this” refers to the new Array showLength.call(new Array(10)); // Alerts 10!
Slide 109: First, a review of an object • This is an object Person = function(fn, ln) {}
Slide 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”
Slide 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; } }
Slide 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 + " " + lastName; } }
Slide 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; }
Slide 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
Slide 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;
Slide 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); var ws = r.widthSquared(); -- OUR OLD Rectangle OBJECT // 100;
Slide 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();
Slide 118: Inheritance – Simple Approach • Why this might be bad – Explicit reference to Rectangle in the constructor – brittle PositionedRectangle = function(x,y,w,h) { Rectangle.call(this,w,h); <!-- … --> ork Will still w s ase in most c – Constructor assigned to prototype – potentially brittle at compile-time if DOM is being drawn PositionedRectangle.prototype = new Rectangle();
Slide 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 compiletime constructor execution base constructor pointer base method pointers
Slide 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
Slide 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!
Slide 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(); customer2.pay(); var f = Customer.oldFunction Customer.oldFunction = function() { f.call(this); somethingElse(); }
Slide 123: ADVANCED JAVASCRIPT Ajax
Slide 124: Ajax Versus Traditional
Slide 125: XMLHttpRequest • The core of Ajax IE 6 and 7 var xhr = null; try { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) { xhr = new XMLHttpRequest(); Everybody Else } xhr.open("GET", "http://www.example.com/myResource", false); xhr.send(null); showResult(xhr); Async = false
Slide 126: XHR Factory • Use Factory pattern to create XHR objects in a cross-browser manner xhrFactory = { create: function() { try { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } cstch(e) { xhr = new XMLHttpRequest(); } return xhr; } } var xhr = xhrFactory.create();
Slide 127: Synchronous Requests • Simplest case • However, JavaScript thread is locked! var xhr = xhrFactory.create(); xhr.open("GET", “http://www.example.com/resource”, false); var response = xhr.send(null); Async = false
Slide 128: Asynchronous Requests • Use async requests to prevent locking the JavaScript thread xhr.open("GET", “http://www.example.com/resource”, true); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { Async = true if (xhr.status == 200) { // deal with the response } Regular HTTP status code } }
Slide 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”);
Slide 130: Data Types • POST data to the server as either XML or form encoded data • Use XHR setRequestHeader() method XML xhr.setRequestHeader("Content-Type","text/xml"); Form data xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
Slide 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!
Slide 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 • HTML – No rendering logic on client – bandwidth considerations what Just yse r….. you prefe
Slide 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);
Slide 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);
Slide 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);
Slide 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);
Slide 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”}] -->
Slide 138: ADVANCED JAVASCRIPT DOM Events
Slide 139: DOM Events • Native Event object contains information about the event • Two approaches to defining events: – Inline – Unobtrusive • Unobtrusive approach requires crossbrowser event attachment
Slide 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
Slide 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="ie_onload.js"></script><![endif]--> The rest window.onload = init;
Slide 142: Inline Events • Most simple event attachment <div onmouseover=“swapColor(event)” onmouseout=“swapColor(event)”></div> • What about separating our control from our view?
Slide 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’;};
Slide 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”
Slide 145: JavaScript Gotcha’s Event Object Internet Explorer W3C document.documentElement.clientHeight clientX / Y returns the event coordinates without the document scroll position taken into account, whereas pageX / Y does take scrolling into account. The HTML element to which the event handler was attached. Various key event modifiers to check if ctrlKey, shiftKey ctrlKey, shiftKey the Shift or Ctrl key are pressed. The HTML element on which the event actually took place. Both properties are supported in Opera and Safari. The event type without the “on” prefix. from is used only for mouseover and mouseout events. Both properties are supported in Opera and Safari clientX / Y N/A keyCode, altKey, ctrlKey, shiftKey srcElement type fromElement / toElement clientX / Y, pageX / Y currentTarget keyCode, altKey, ctrlKey, shiftKey target type relatedTarget
Slide 146: Event Questions • How do you access the Event object? • What does “this” refer to in the event handler function?
Slide 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; }
Slide 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 }
Slide 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 Detects IE if (elem.attachEvent) { // 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 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
Slide 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

   
Time on Slide Time on Plick
Slides per Visit Slide Views Views by Location