Your SlideShare is downloading. ×
0
Javascript Introduction Vu Viet Phuong - Portal Team
<ul><li>Help to approach Javascript easier </li></ul>Objective <ul><li>Prepare to work with eXo javascript framework </li>...
<ul><li>Characteristic of Javascript language </li></ul>Subject <ul><li>OOP with Javascript </li></ul><ul><li>Javascript a...
Characteristic of Javascript language
What is Javascript ? Netscape initially introduced the language under the name LiveScript in an early beta release of Navi...
What can We do with it ?   Provide interactive content on your Web pages ( embeded in HTML page using <script> tag )   Muc...
What Javascript can’t do Javascript are confined to browser-related and HTML-related tasks ->  it does not have features t...
Quick introduction of basic programming <ul><ul><ul><li>JavaScript is similar to so many other languages:  </li></ul></ul>...
Quick introduction of basic programming <ul><ul><li>Flow control : (if-else, switch) </li></ul></ul><ul><li>if (expression...
Quick introduction of basic programming Script Execution Order :  interpreted line by line as it is found in the page Case...
Data type <ul><li>  Data Type :  </li></ul><ul><li>- Primitive  data types: number, string, boolean, undefined, null </li>...
Data type Automatic Type Conversion :  M ost powerful features of JavaScript, as well as the most dangerous for the sloppy...
Functions <ul><li>  Function creation syntax  :   </li></ul><ul><li>function Add(x, y)  </li></ul><ul><li>{ var sum = x + ...
Context, Scope and Closures <ul><li>  Context  :  always be in some form on context (an object within which it's operating...
Object-Oriented Programming with JavaScript
Object in Javascript <ul><ul><li>Objects are the fundamental units of JavaScript </li></ul></ul><ul><ul><li>EVERYTHING exc...
Object creation 1. Using  new Object() employee = new Object() employee.name = &quot;Tim&quot;; employee.say = function() ...
Object creation 3. Object Constructor : - Regular JavaScript function - The difference is that, it is called via 'new' ope...
Object creation Now, since User() is just a function what happens when we treat it as such?   User( &quot;Test&quot; );  /...
Prototype Prototyping is the key to understanding the inheritance concept “ prototype”  is a property of every function. S...
Inheritance <ul><ul><li>Inheritance is the ability to have properties from “Super Class” </li></ul></ul><ul><ul><li>Set  p...
Encapsulation <ul><ul><li>Objects interact with each other via call method, and don't know what is happening inside </li><...
Polymorphism <ul><ul><li>Polymorphism  : is a programming language feature that allows values of different data types to b...
<ul><ul><li>Namespace help us to avoid name conflic </li></ul></ul><ul><ul><li>Javascript, natively doesn't provide namesp...
Javascript and DOM
<ul><li>DOM : Document Object Model  </li></ul><ul><ul><li>Dom is programming interface for HTML and XML documents </li></...
<ul><ul><li>There are a number of possible values  </li></ul></ul><ul><ul><li>The three that you’ll encounter the most are...
API document and window objects are the objects whose interfaces  you generally use most often in DOM programming   window...
document The document provides methods for creating and manipulating all of the document's child nodes, or elements Creati...
CSS <ul><ul><li>There are two problems that you encounter when working with CSS properties on DOM elements </li></ul></ul>...
DOM Event <ul><ul><li>Events are actions on DOM that can be detected by JavaScript </li></ul></ul><ul><ul><li>Every elemen...
Event Phases <ul><ul><li>Javascript events are executed in 2 phases  </li></ul></ul><ul><ul><li>Capturing : event moving d...
Event object <ul><ul><li>Contains contextual information about the current event </li></ul></ul><ul><ul><li>IE’s implement...
Control event <ul><ul><li>Overriding the Browser’s Default Action : </li></ul></ul><ul><li>if ( e && e.preventDefault ) </...
Event handler <ul><ul><li>Traditional Binding </li></ul></ul><ul><li>document.body.onclick(handler); </li></ul><ul><ul><li...
Ajax
Definition Ajax (Asynchronous JavaScript and XML) AJAX uses a combination of :  DOM   XMLHttpRequest   XML  is sometimes u...
How it work Request process can be handled  asynchronously Then a  SMALL  portion of desired results can be loaded upon co...
Make request <ul><ul><li>Create XMLHttpRequest Object </li></ul></ul><ul><li>- Internet Exployer 5, 6: </li></ul><ul><li> ...
Send data <ul><ul><li>Serializing Data:  </li></ul></ul><ul><li>function User() {  name: &quot;John&quot;,  last: &quot;Re...
Handle response <ul><ul><li>readyState property :  request lifecycle </li></ul></ul><ul><li>0 : uninitialized </li></ul><u...
Update UI Reading the Resulting Data responseXML :  This property will contain a reference to a precomputed DOM document r...
Javascript Performance
Some tips <ul><ul><li>DOM access :  Interaction with the DOM is usually slower than normal JavaScript code   </li></ul></u...
Upcoming SlideShare
Loading in...5
×

eXo SEA - JavaScript Introduction Training

2,282

Published on

JavaScript introduction presented by Phuong - eXo Portal team.

Published in: Technology
1 Comment
3 Likes
Statistics
Notes
No Downloads
Views
Total Views
2,282
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
26
Comments
1
Likes
3
Embeds 0
No embeds

No notes for slide

Transcript of "eXo SEA - JavaScript Introduction Training"

  1. 1. Javascript Introduction Vu Viet Phuong - Portal Team
  2. 2. <ul><li>Help to approach Javascript easier </li></ul>Objective <ul><li>Prepare to work with eXo javascript framework </li></ul>
  3. 3. <ul><li>Characteristic of Javascript language </li></ul>Subject <ul><li>OOP with Javascript </li></ul><ul><li>Javascript and DOM </li></ul><ul><li>Ajax </li></ul><ul><li>Javascript performance </li></ul>
  4. 4. Characteristic of Javascript language
  5. 5. What is Javascript ? Netscape initially introduced the language under the name LiveScript in an early beta release of Navigator 2.0 in 1995 Some characteristics : - Script language - Interpreted - Changing rapidly and Cross-platform support is not consistent JavaScript is the most popular scripting language on the internet
  6. 6. What can We do with it ? Provide interactive content on your Web pages ( embeded in HTML page using <script> tag ) Much of its power is derived from both the built-in and document objects provided by the browser Control Document Appearance and Content : document.write(), DOM... Control the Browser : window.alert(); window.open(); window.close()... Interact with the User : ability to define &quot;event handlers&quot;
  7. 7. What Javascript can’t do Javascript are confined to browser-related and HTML-related tasks -> it does not have features that would be required for standalone languages Some lack of features : Graphics capabilities Reading or writing of files Multithreading , except whatever comes implicitly from the web browser's internal use of threads
  8. 8. Quick introduction of basic programming <ul><ul><ul><li>JavaScript is similar to so many other languages: </li></ul></ul></ul><ul><li>Arithmetic and logical operators are part of the language </li></ul><ul><li>Flow-control constructs such as if, while, and switch </li></ul>Example : - Arithmetic Operators : + - * / % The addition operator (+) has a different behavior when operating on strings as opposed to numbers - Comparison Operators : > < >= <= != == === alert(“10” == 10) //display true alert(“10” === 10) //display false - typeof operator : alert( typeof “some string”); //display string http://www.techotopia.com/index.php/JavaScript_Operators
  9. 9. Quick introduction of basic programming <ul><ul><li>Flow control : (if-else, switch) </li></ul></ul><ul><li>if (expression) </li></ul><ul><li>statement; </li></ul><ul><li>else </li></ul><ul><li>statement; </li></ul><ul><ul><li>Loops : (while, do-while, for) </li></ul></ul><ul><ul><li>Loop control (break and continue) </li></ul></ul><ul><ul><li>Object-Related Statements: </li></ul></ul><ul><li>with Statement : a shorthand notation when referencing objects </li></ul><ul><li>w ith(document) {write(“Hello World”);} </li></ul><ul><li>for…in : used to loop through an object’s properties </li></ul><ul><li>for (pros in document) {document.write(pros);} </li></ul>http://en.wikipedia.org/wiki/JavaScript_syntax
  10. 10. Quick introduction of basic programming Script Execution Order : interpreted line by line as it is found in the page Case Sensitivity : JavaScript is case-sensitive: keywords, operators.... Statement Delimiters : Semicolons and Returns Declare Variables : - var keyword - implicit declaration
  11. 11. Data type <ul><li> Data Type : </li></ul><ul><li>- Primitive data types: number, string, boolean, undefined, null </li></ul><ul><li>- Composite types: objects, arrays, and functions </li></ul><ul><li> Dynamic Typing : T ype is inferred from the variable’s content </li></ul><ul><li>var test = “10”; //It's a string </li></ul><ul><li>test = 10; //It's a number now </li></ul>
  12. 12. Data type Automatic Type Conversion : M ost powerful features of JavaScript, as well as the most dangerous for the sloppy programmer window.alert(“10” - 3); -> result : 7 Force the conversion using methods like toString() or parseInt() DynamicTyping.html
  13. 13. Functions <ul><li> Function creation syntax : </li></ul><ul><li>function Add(x, y) </li></ul><ul><li>{ var sum = x + y; return sum; } </li></ul>var test = new Function(“alert('test')”); var test = function() {alert('test')}; <ul><li> How to deal with arguments : </li></ul><ul><ul><li>length property </li></ul></ul><ul><ul><li>arguments [] property </li></ul></ul>FunctionCreation.html
  14. 14. Context, Scope and Closures <ul><li> Context : always be in some form on context (an object within which it's operating) </li></ul><ul><li>the way context works is through the this variable </li></ul><ul><li> Closures : I nner functions can refer to the variables in their outer enclosing function </li></ul><ul><li> Curring effect </li></ul><ul><li> Hide variables from global scope </li></ul><ul><li> Scope : is tricky feature. In Javascript, scope is kept within functions </li></ul>Context.html Scope.html Closures.html http://jibbering.com/faq/notes/closures/
  15. 15. Object-Oriented Programming with JavaScript
  16. 16. Object in Javascript <ul><ul><li>Objects are the fundamental units of JavaScript </li></ul></ul><ul><ul><li>EVERYTHING except primative type in JavaScript is object </li></ul></ul><ul><ul><li>There are three object categories in JavaScript: </li></ul></ul><ul><ul><ul><li>Native Objects </li></ul></ul></ul><ul><ul><ul><li>Host Objects </li></ul></ul></ul><ul><ul><ul><li>User-Defined Objects </li></ul></ul></ul>
  17. 17. Object creation 1. Using new Object() employee = new Object() employee.name = &quot;Tim&quot;; employee.say = function() { alert('hello'); } 2. Using Literal Notation employee = { name : &quot;Tim&quot;, say : function() { alert('hello') } }; NOT reusable- we cannot easily initialize different versions of the created object
  18. 18. Object creation 3. Object Constructor : - Regular JavaScript function - The difference is that, it is called via 'new' operator, without this, it just likes other javascript method // it to the current context function User( name ) { this.name = name; } // Create a new instance of that function var me = new User( &quot;My Name&quot; ); 3. Object Constructor : - Regular JavaScript function - The difference is that, it is called via 'new' operator, without this, it just likes other javascript method
  19. 19. Object creation Now, since User() is just a function what happens when we treat it as such? User( &quot;Test&quot; ); // Since its 'this' context wasn't set // it defaults to the global 'window' alert( window.name == &quot;Test&quot; ); // display true ObjectCreation.html
  20. 20. Prototype Prototyping is the key to understanding the inheritance concept “ prototype” is a property of every function. Since constructor is also function, it's a property of constructor too function User(){}; var test = new User(); User.prototype.say = function() {alert('hello')}; test.say(); //display hello ObjectCreation_Prototype.html
  21. 21. Inheritance <ul><ul><li>Inheritance is the ability to have properties from “Super Class” </li></ul></ul><ul><ul><li>Set prototype property of constructor to an “super class” object </li></ul></ul>-> “ sub class” object will have access to “super class” properties function SuperClass() { this.superHello = function() {alert(“super hello”)} } function SubClass(){} SubClass.prototype = new SuperClass(); Inheritance.html
  22. 22. Encapsulation <ul><ul><li>Objects interact with each other via call method, and don't know what is happening inside </li></ul></ul><ul><ul><li>Private : only accessible to other private methods or privileged methods </li></ul></ul>function Bean() { var name = &quot;test&quot;; //Getter this.getName = function() {return name}; //Setter this.setName = function(newName) {name = newName}; } Encapsulation.html
  23. 23. Polymorphism <ul><ul><li>Polymorphism : is a programming language feature that allows values of different data types to be handled using a uniform interface </li></ul></ul><ul><ul><li>In java, we can achieve this by implementing an interface </li></ul></ul><ul><ul><li>In weakly typed languages like JavaScript, types are implicitly polymorphic </li></ul></ul>http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming
  24. 24. <ul><ul><li>Namespace help us to avoid name conflic </li></ul></ul><ul><ul><li>Javascript, natively doesn't provide namespace feature </li></ul></ul>Namespacing Workaround for this : var = { DOMUtil : { }, … . }; //After define DOMUtil, we use it in namespace like that eXo.core.DOMUtil = new DOMUtil() ; Namespace.html
  25. 25. Javascript and DOM
  26. 26. <ul><li>DOM : Document Object Model </li></ul><ul><ul><li>Dom is programming interface for HTML and XML documents </li></ul></ul><ul><ul><li>It provides a structured representation of the document </li></ul></ul>Javascript and DOM <html> <head>...</head> <body> <h1>Hello World!</h1> </body> </html> // Does not work! -> text is also consisdered a node document.documentElement.firstChild.nextSibling.firstChild DOMExample.html
  27. 27. <ul><ul><li>There are a number of possible values </li></ul></ul><ul><ul><li>The three that you’ll encounter the most are the following: </li></ul></ul><ul><li>Element (nodeType = 1), Text (3), Document (9) </li></ul>Node types http://www.javascriptkit.com/domref/nodetype.shtml
  28. 28. API document and window objects are the objects whose interfaces you generally use most often in DOM programming window object represents the window itself window.alert(); window.open(); window.scrollTo() document property of window points to the DOM document loaded in that window http://www.w3schools.com/jsref/obj_window.asp
  29. 29. document The document provides methods for creating and manipulating all of the document's child nodes, or elements Creating and Retrieving elements: document.getElementById(id), document.createElement(name) Get and Set Attributes: document.getAttribute(name), document.setAttribute(name,val) https://developer.mozilla.org/en/Gecko_DOM_Reference Document.html
  30. 30. CSS <ul><ul><li>There are two problems that you encounter when working with CSS properties on DOM elements </li></ul></ul><ul><ul><li>Second, can't get pre-set style. We must get the computed style </li></ul></ul><ul><ul><li>First, JavaScript requires that you specify the unit of size for setting any dimensional property </li></ul></ul><ul><li>document.getElementById(“table”).style.width = “200 px ”; </li></ul>StyleTest.html
  31. 31. DOM Event <ul><ul><li>Events are actions on DOM that can be detected by JavaScript </li></ul></ul><ul><ul><li>Every element on a web page has certain events which can trigger JavaScript functions </li></ul></ul><ul><ul><li>Examples of events: </li></ul></ul><ul><li>- A mouse click </li></ul><ul><li>- A web page or an image loading </li></ul><ul><li>- Mousing over a hot spot on the web page </li></ul>
  32. 32. Event Phases <ul><ul><li>Javascript events are executed in 2 phases </li></ul></ul><ul><ul><li>Capturing : event moving down the DOM tree to the element that instantiated event </li></ul></ul><ul><ul><li>Bubbling phase traverses up DOM tree to the root element </li></ul></ul>Bubbing.html Capturing.html
  33. 33. Event object <ul><ul><li>Contains contextual information about the current event </li></ul></ul><ul><ul><li>IE’s implementation is different from the W3C’s specification </li></ul></ul>function eventHandler(evt) { var e = window.event || evt; ... } <ul><ul><li>Default behaviour : </li></ul></ul><ul><li>Browser has some default actions that will always occur </li></ul><ul><li>click <a> element -> redirect to other page </li></ul><ul><li>press key on textbox -> display chars on textbox </li></ul>
  34. 34. Control event <ul><ul><li>Overriding the Browser’s Default Action : </li></ul></ul><ul><li>if ( e && e.preventDefault ) </li></ul><ul><li>e. preventDefault (); </li></ul><ul><li>else </li></ul><ul><li>//IE </li></ul><ul><li>window.event. returnValue = false; </li></ul><ul><ul><li>Stop bubbling : </li></ul></ul><ul><li>if ( e && e.stopPropagation ) </li></ul><ul><li>e. stopPropagation (); </li></ul><ul><li>else </li></ul><ul><li>window.event. cancelBubble = true; </li></ul>OverrideDefaultAction.html StopBubbling.html
  35. 35. Event handler <ul><ul><li>Traditional Binding </li></ul></ul><ul><li>document.body.onclick(handler); </li></ul><ul><ul><li>W3C method of binding event handlers </li></ul></ul><ul><li>document.body.addEventListener('click', handler, false); </li></ul><ul><ul><li>IE’s method </li></ul></ul><ul><li>document.body.attachEvent(' onclick ', myKeyPressHandler); </li></ul>https://developer.mozilla.org/en/DOM/event
  36. 36. Ajax
  37. 37. Definition Ajax (Asynchronous JavaScript and XML) AJAX uses a combination of : DOM XMLHttpRequest XML is sometimes used as the format for transferring data between the server and client, although any format will work
  38. 38. How it work Request process can be handled asynchronously Then a SMALL portion of desired results can be loaded upon completion
  39. 39. Make request <ul><ul><li>Create XMLHttpRequest Object </li></ul></ul><ul><li>- Internet Exployer 5, 6: </li></ul><ul><li> new ActiveXObject(&quot;Microsoft.XMLHTTP&quot;); </li></ul><ul><li>- IE7+, Firefox, Chrome, Opera, Safari : </li></ul><ul><li> new XMLHttpRequest(); </li></ul><ul><ul><li>Establishing a Connection : GET or POST request </li></ul></ul><ul><li>// Open the socket </li></ul><ul><li>ajx.open(&quot;GET&quot;, &quot;/some/url&quot;, true); </li></ul><ul><li>// Establish the connection to the server </li></ul><ul><li>ajx.send(); </li></ul>
  40. 40. Send data <ul><ul><li>Serializing Data: </li></ul></ul><ul><li>function User() { name: &quot;John&quot;, last: &quot;Resig&quot; } </li></ul><ul><li>// Serialized form </li></ul><ul><li>serObj = name=John&last=Resig </li></ul><ul><ul><li>Request method : GET </li></ul></ul><ul><li>ajx.open(&quot;GET&quot;, &quot;/some/url?&quot; + serObj , true); </li></ul><ul><li>ajx.send(); </li></ul><ul><ul><li>Request method : POST </li></ul></ul><ul><li>ajx.open(&quot;POST&quot;, &quot;/some/url&quot;, true); </li></ul><ul><li>ajx. setRequestHeader ( &quot;Content-Type&quot;, </li></ul><ul><li>&quot; application/x-www-form-urlencoded &quot;); </li></ul><ul><li>ajx.send( serObj ); </li></ul>
  41. 41. Handle response <ul><ul><li>readyState property : request lifecycle </li></ul></ul><ul><li>0 : uninitialized </li></ul><ul><li>1 : connection establised </li></ul><ul><li>2 : request received </li></ul><ul><li>3 : processing </li></ul><ul><li>4 : finished </li></ul><ul><li> </li></ul><ul><ul><ul><li>onreadystatechange property </li></ul></ul></ul><ul><li>Successful response codes: 200 <= ajx.status < 300 </li></ul><ul><li>Not modified response : 304 (Safari : undefined) </li></ul><ul><li>Every other codes will be considered error </li></ul>
  42. 42. Update UI Reading the Resulting Data responseXML : This property will contain a reference to a precomputed DOM document responseText : This property contains a reference to the raw text string of data returned by the server ajx.onreadystatechange = function(){ if ( ajx.readyState == 4 ) { if ( ajx.status >= 200 && ajx.status < 300 ) { var scores = document.getElementById(&quot;testDiv&quot;); scores.innerText = ajx. responseText ; } } }; Example http://www.learn-ajax-tutorial.com/
  43. 43. Javascript Performance
  44. 44. Some tips <ul><ul><li>DOM access : Interaction with the DOM is usually slower than normal JavaScript code </li></ul></ul><ul><ul><li>for-in loops : most JS environments have slow implementation </li></ul></ul><ul><ul><li>eval and Function constructor : </li></ul></ul><ul><li>avoid using because overhead is involved in script evaluation </li></ul><ul><li>//expensive operations </li></ul><ul><li>var func = new Function(“alert('test')”); </li></ul><ul><ul><li>Pass functions , not strings, to setTimeout () and setInterval () </li></ul></ul>http://wiki.forum.nokia.com/index.php/JavaScript_Performance_Best_Practices
  1. A particular slide catching your eye?

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

×