+ All Categories
Home > Documents > AJAX Coursework

AJAX Coursework

Date post: 04-Apr-2018
Category:
Upload: rataro123456
View: 222 times
Download: 0 times
Share this document with a friend

of 593

Transcript
  • 7/29/2019 AJAX Coursework

    1/592

    Ajax Basics

    Michael Galpin, eBayhttp://fupeg.blogspot.com

  • 7/29/2019 AJAX Coursework

    2/592

    Course Agenda Jump In

    > Ajax Basics> Ajax Frameworks

    Fundamentals

    >Intro to JavaScript

    > Advanced JavaScript

    > JavaScript Cookbook

    Frameworks

    > Prototype

    > Dojo

    > Google Web Toolkit

    > Direct Web Remoting

  • 7/29/2019 AJAX Coursework

    3/592

    Ajax Basics : Agenda1.What is Rich User Experience?

    2.Rich Internet Application (RIA) Technologies

    3.Ajax: Real-life examples & Usage cases

    4.What is and Why Ajax?

    5.Technologies used in Ajax6.Anatomy of Ajax operation

    7.XMLHttpRequest Methods & Properties

    8.DOM APIs & InnerHTML9.Ajax Security

    10.JavaScript debugging tools

    11.Current issues and Future

  • 7/29/2019 AJAX Coursework

    4/592

    1. Rich User Experience1. Rich User Experience

    for Web Applicationfor Web Application

  • 7/29/2019 AJAX Coursework

    5/592

    Rich User Experience

    Take a look at a typical desktop application

    (Spreadsheet app, etc.)

    The program responses intuitively and quickly

    The program gives a user meaningful feedback's

    instantly>A cell in a spreadsheet changes color when

    you hover your mouse over it

    > Icons light up as mouse hovers them

    Things happen naturally

    > No need to click a button or a link to trigger anevent

  • 7/29/2019 AJAX Coursework

    6/592

    Characteristics of Conventional WebApplications

    Click, wait, and refresh user interaction> Page refreshes from the server needed for all

    events, data submissions, and navigation

    Synchronous request/responsecommunication model

    > The user has to wait for the response

    Page-driven: Workflow is based on pages> Page-navigation logic is determined by the

    server

  • 7/29/2019 AJAX Coursework

    7/592

    Issues of Conventional Web Application Interruption of user operation

    > Users cannot perform any operation while waiting for aresponse

    Loss of operational context during refresh

    > Loss of information on the screen

    > Loss of scrolled position

    No instant feedback's to user activities

    > A user has to wait for the next page

    Constrained by HTML> Lack of useful widgets

    These are the reasons why Rich Internet

    Application (RIA) technologies were born.

  • 7/29/2019 AJAX Coursework

    8/592

    2. Rich Internet2. Rich Internet

    Application (RIA) TechnologiesApplication (RIA) Technologies

  • 7/29/2019 AJAX Coursework

    9/592

    Rich Internet Application (RIA)Technologies

    Java Applet

    Adobe Flash/FlexAjax (JavaScript and DHTML)

    Microsoft Silverlight

    JavaFX

  • 7/29/2019 AJAX Coursework

    10/592

    Adobe Flash/Flex Designed for playing interactive movies

    Programmed with ActionScript

    Pros:

    > Good for displaying vector graphics

    > Excellent tooling

    > Browser independent

    Cons:

    > Browser needs a Flash plug-in

    >ActionScript is proprietary

  • 7/29/2019 AJAX Coursework

    11/592

    Ajax DHTML = JavaScript + DOM + CSS

    DHTML plus Asynchronous communication capabilitythrough XMLHttpRequest

    Pros

    > Most viable RIA technology so far

    > Tremendous industry momentum

    > Several toolkits and frameworks are emerging

    > No need to download code & no plug-in required

    Cons

    > Still browser incompatibility

    > JavaScript is hard to maintain and debug

  • 7/29/2019 AJAX Coursework

    12/592

    3. Ajax:3. Ajax:

    Real-life Examples &Real-life Examples &

    UsecasesUsecases

  • 7/29/2019 AJAX Coursework

    13/592

    Real-Life Examples of Ajax Apps

    Outlook Web Access GMail http://mail.google.com/

    Flickrhttp://flickr.com/

    Facebook http://www.facebook.com/

    NetFlix http://www.netflix.com/

    #(non-Ajax sites) < #(Ajax sites) ?

    http://mail.google.com/http://flickr.com/http://www.facebook.com/http://www.facebook.com/http://flickr.com/http://mail.google.com/
  • 7/29/2019 AJAX Coursework

    14/592

    Key Aspects of Google MapsA user can drag the entire map by using

    the mouse> Instead of clicking on a button or something

    The action that triggers the download of

    new map data is not a specific click on alink but a moving the map around

    Behind the scene - Ajax is used

    > The map data is requested and downloadedasynchronously in the background

    Other parts of the page remains the same

    > No loss of operational context

  • 7/29/2019 AJAX Coursework

    15/592

    Use cases for Ajax Real-time server-side input form data

    validation> User IDs, serial numbers, postal codes

    > Removes the need to have validation logic at

    both client side for user responsiveness and atserver side for security and other reasons

    Auto-completion

    > Email address, name, or city name may beauto-completed as the user types

    Master detail operation

    > Based on a user selection, more detailed

    information can be fetched and displayed

  • 7/29/2019 AJAX Coursework

    16/592

    Use cases for AJAXAdvanced GUI widgets and controls

    > Controls such as tree controls, menus, andprogress bars may be provided that do notrequire page refreshes

    Refreshing data

    > HTML pages may poll data from a server forup-to-date data such as scores, stock quotes,weather, or application-specific data

    Simulating server side notification>An HTML page may simulate a server-side

    notification by polling the server in the

    background (Comet/Reverse Ajax)

  • 7/29/2019 AJAX Coursework

    17/592

    Ajax:Ajax: DemoDemoAjax Sample AppsAjax Sample Apps

  • 7/29/2019 AJAX Coursework

    18/592

    4. Ajax:4. Ajax:

    What is and Why Ajax?What is and Why Ajax?

  • 7/29/2019 AJAX Coursework

    19/592

    Why Ajax? Intuitive and natural user interaction

    > No clicking required

    > Mouse movement is a sufficient event trigger

    "Partial screen update" replaces the "click, wait, andrefresh" user interaction model

    > Only user interface elements that contain newinformation are updated (fast response)

    > The rest of the user interface remains displayedwithout interruption (no loss of operational context)

    Data-driven (as opposed to page-driven)

    > UI is handled in the client while the server providesdata

  • 7/29/2019 AJAX Coursework

    20/592

    Why Ajax?

    Asynchronous communication replaces"synchronous request/response model."

    >A user can continue to use the applicationwhile the client program requests informationfrom the server in the background

    > Separation of displaying from data fetching

  • 7/29/2019 AJAX Coursework

    21/592

  • 7/29/2019 AJAX Coursework

    22/592

  • 7/29/2019 AJAX Coursework

    23/592

    5. Ajax:5. Ajax:Technologies UsedTechnologies Used

    in Ajaxin Ajax

  • 7/29/2019 AJAX Coursework

    24/592

    Technologies Used In Ajax Javascript

    > Dynamic language

    > JavaScript function is called when an event in a page occurs

    > Glue for the whole Ajax operation

    DOM

    > API for accessing and manipulating structured documents

    > Represents the structure of XML and HTML documents

    CSS

    > Allows for a clear separation of the presentation style from thecontent and may be changed programmatically by JavaScript

    XMLHttpRequest

    > JavaScript object that performs asynchronous interaction with theserver

  • 7/29/2019 AJAX Coursework

    25/592

    XMLHttpRequest JavaScript object, invented by Microsoft

    Adopted by modern browsers

    > Mozilla, Firefox, Safari, and Opera

    Communicates with a server via standardHTTP GET/POST

    XMLHttpRequest object works in thebackground for performing asynchronous

    communication with the backend server> Does not interrupt user operation

  • 7/29/2019 AJAX Coursework

    26/592

    Server-Side Ajax Request Processing Server programming model remains the

    same> It receives standard HTTP GETs/POSTs

    > Can use JSP, PHP, ASP.NET ...

    With minor constraints> More frequent and finer-grained requests from

    client

    > Response content type can be> text/xml

    > text/plain

    > text/json

    > text/javascript

  • 7/29/2019 AJAX Coursework

    27/592

    6. Ajax:6. Ajax:

    Anatomy OfAnatomy Of

    Ajax InteractionAjax Interaction

    using Data Validationusing Data Validation

    Sample ApplicationSample Application

  • 7/29/2019 AJAX Coursework

    28/592

    Anatomy of an Ajax Interaction(Data Validation Example)

  • 7/29/2019 AJAX Coursework

    29/592

    Steps of AJAX Operation1.A client event occurs

    2.An XMLHttpRequest object is created3.The XMLHttpRequest object is configured

    4.The XMLHttpRequest object makes an async.request

    5.The ValidateServlet returns an XML documentcontaining the result

    6.The XMLHttpRequest object calls the

    callback() function and processes the result7.The HTML DOM is updated

    C

  • 7/29/2019 AJAX Coursework

    30/592

    1. A Client event occursA JavaScript function is called as the result of

    an event

    Example: validateUserId() JavaScript functionis mapped as a event handler to a onkeyupevent on input form field whose id is set to

    userid

  • 7/29/2019 AJAX Coursework

    31/592

    2. An XMLHttpRequest object is createdvar req;

    function initRequest() {if (window.XMLHttpRequest) {req = new XMLHttpRequest();

    } else if (window.ActiveXObject) {isIE = true;req = new ActiveXObject("Microsoft.XMLHTTP");

    }}

    function validateUserId() { initRequest();

    req.onreadystatechange = processRequest;if (!target) target = document.getElementById("userid");var url = "validate?id=" + escape(target.value);req.open("GET", url, true);req.send(null);

    }

    3 A XMLHtt R t bj t i

  • 7/29/2019 AJAX Coursework

    32/592

    3. An XMLHttpRequest object isconfigured with a callback function

    var req;

    function initRequest() {if (window.XMLHttpRequest) {req = new XMLHttpRequest();

    } else if (window.ActiveXObject) {isIE = true;req = new ActiveXObject("Microsoft.XMLHTTP");

    }}

    function validateUserId() {initRequest();

    req.onreadystatechange = processRequest; // callback functionif (!target) target = document.getElementById("userid");var url = "validate?id=" + escape(target.value);req.open("GET", url, true);req.send(null);

    }

    4 XMLHtt R t bj t k

  • 7/29/2019 AJAX Coursework

    33/592

    4. XMLHttpRequest object makes an async.requestfunction initRequest() {

    if (window.XMLHttpRequest) {req = new XMLHttpRequest();

    } else if (window.ActiveXObject) {isIE = true;req = new ActiveXObject("Microsoft.XMLHTTP");

    }

    }function validateUserId() {

    initRequest();req.onreadystatechange = processRequest;

    if (!target) target = document.getElementById("userid");var url = "validate?id=" + escape(target.value);req.open("GET", url, true);req.send(null);

    }

    URL is set to validate?id=greg

  • 7/29/2019 AJAX Coursework

    34/592

    5. The ValidateServlet returns an XMLdocument containing the results (Server)

    public void doGet(HttpServletRequest request, HttpServletResponseresponse)

    throws IOException, ServletException {

    String targetId = request.getParameter("id");

    if ((targetId != null) && !accounts.containsKey(targetId.trim())) {response.setContentType("text/xml");response.setHeader("Cache-Control", "no-cache");response.getWriter().write("true");

    } else {response.setContentType("text/xml");response.setHeader("Cache-Control", "no-cache");response.getWriter().write("false");

    }}

    6 XMLHttpRequest object calls callback()

  • 7/29/2019 AJAX Coursework

    35/592

    6. XMLHttpRequest object calls callback()function and processes the result The XMLHttpRequest object was

    configured to call the processRequest()function when there is a state change tothe readyState of the XMLHttpRequest

    object

    function processRequest() {if (req.readyState == 4) {

    if (req.status == 200) {var message = ...;

    ...

    7 Th HTML DOM i d t d

  • 7/29/2019 AJAX Coursework

    36/592

    7. The HTML DOM is updated JavaScript technology gets a reference to

    any element in a page using DOM API

    The recommended way to gain a referenceto an element is to call

    > document.getElementById("userIdMessage"),where "userIdMessage" is the ID attribute of anelement appearing in the HTML document

    JavaScript technology may now be used to

    modify the element's attributes; modify theelement's style properties; or add, remove,or modify child elements

    1.

  • 7/29/2019 AJAX Coursework

    37/592

    p yp j p2. function setMessageUsingDOM(message) {3. var userMessageElement = document.getElementById("userIdMessage");4. var messageText;5. if (message == "false") {6. userMessageElement.style.color = "red";

    7. messageText = "Invalid User Id";8. } else {9. userMessageElement.style.color = "green";10. messageText = "Valid User Id";11. }12. var messageBody = document.createTextNode(messageText);13. // if the messageBody element has been created simple replace it otherwise

    14. // append the new element15. if (userMessageElement.childNodes[0]) {16. userMessageElement.replaceChild(messageBody,17. userMessageElement.childNodes[0]);18. } else {19. userMessageElement.appendChild(messageBody);20. }

    21.}22.23.24. 25.

  • 7/29/2019 AJAX Coursework

    38/592

    7. Ajax:7. Ajax:XMLHttpRequestXMLHttpRequest

    Methods & PropertiesMethods & Properties

  • 7/29/2019 AJAX Coursework

    39/592

    XMLHttpRequest Methods open(HTTP method, URL, syn/asyn)

    >Assigns HTTP method, destination URL, mode send(content)

    > Sends request including string or DOM object data abort()

    > Terminates current request getAllResponseHeaders()> Returns headers (labels + values) as a string

    getResponseHeader(header)

    > Returns value of a given header setRequestHeader(label,value)> Sets Request Headers before sending

    XMLHtt R t P ti

  • 7/29/2019 AJAX Coursework

    40/592

    XMLHttpRequest Properties onreadystatechange

    > Set with an JavaScript event handler that fires at each statechange

    readyState current status of request> 0 = uninitialized

    > 1 = loading> 2 = loaded

    > 3 = interactive (some data has been returned)

    > 4 = complete

    status> HTTP Status returned from server: 200 = OK

  • 7/29/2019 AJAX Coursework

    41/592

    XMLHttpRequest Properties

    responseText> String version of data returned from the server

    responseXML

    > XML document of data returned from the server statusText

    > Status text returned from server

  • 7/29/2019 AJAX Coursework

    42/592

    8. Ajax: DOM API &8. Ajax: DOM API &

    InnerHTMLInnerHTML

  • 7/29/2019 AJAX Coursework

    43/592

    Browser and DOM

    Browsers maintain an object representationof the documents being displayed

    > In the form of Document Object Model (DOM)

    > It is readily available as document JavaScriptobject

    APIs are available that allow JavaScript

    code to modify the DOM programmatically

    DOM APIs vs innerHTML

  • 7/29/2019 AJAX Coursework

    44/592

    DOM APIs vs. innerHTML DOM APIs provide a means for JavaScript code to navigate/modify the

    content in a page

    function setMessageUsingDOM(message) {

    var userMessageElement =document.getElementById("userIdMessage");var messageText;if (message == "false") {

    userMessageElement.style.color = "red";messageText = "Invalid User Id";

    } else {userMessageElement.style.color = "green";messageText = "Valid User Id";

    } var messageBody = document.createTextNode(messageText);

    if (userMessageElement.childNodes[0]) {userMessageElement.replaceChild(messageBody,

    userMessageElement.childNodes[0]);} else {

    userMessageElement.appendChild(messageBody);}

    }

  • 7/29/2019 AJAX Coursework

    45/592

    DOM APIs vs. innerHTML

    Using innerHTML is easier: Sets or retrieves theHTML between the start and end tags of theobject

    function setMessageUsingDOM(message) {

    var userMessageElement =document.getElementById("userIdMessage");var messageText;if (message == "false") {

    userMessageElement.style.color = "red";messageText = "Invalid User Id";

    } else {userMessageElement.style.color = "green";messageText = "Valid User Id";

    } userMessageElement.innerHTML = messageText;

    }

  • 7/29/2019 AJAX Coursework

    46/592

    9. Ajax Security9. Ajax Security

    Ajax Security: Server Side

  • 7/29/2019 AJAX Coursework

    47/592

    Ajax Security: Server SideAjax-based Web applications use the same

    server-side security schemes of regularWeb applications

    > You specify authentication, authorization, anddata protection requirements in your web.xml

    file (declarative) or in your program(programatic)

    Ajax-based Web applications are subject to

    the same security threats as regular Webapplications

    > Cross-site scripting

    > Injection flaw

    Aj S it Cli t Sid

  • 7/29/2019 AJAX Coursework

    48/592

    Ajax Security: Client Side JavaScript code is visible to a user/hacker

    > Hacker can use the JavaScript code forinferring server side weaknesses

    > Obfustication or compression can be used

    JavaScript code is downloaded from theserver and executed (eval) at the client

    > Can compromise the client by mal-intendedcode

    Downloaded JavaScript code isconstrained by sand-box security model

  • 7/29/2019 AJAX Coursework

    49/592

    10. JavaScript Development10. JavaScript Development

    ToolsTools

  • 7/29/2019 AJAX Coursework

    50/592

    Development Tools on Mozilla Browser

    Mozilla FireBug debugger (add-on)> This is the most comprehensive and most useful

    JavaScript debugger

    Mozilla JavaScript console

    Mozilla DOM inspector (comes with Firefoxpackage)

    Mozilla Venkman JavaScript debugger (add-

    on)

    Web Developer Toolbar (add-on)

    > DOM/CSS inspection, tweaking, debugging

  • 7/29/2019 AJAX Coursework

    51/592

    Mozilla FireBug Debugger Spy on XMLHttpRequest traffic

    JavaScript debugger for stepping through code one lineat a time

    Inspect HTML source, computed style, events, layoutand the DOM

    Status bar icon shows you when there is an error in aweb page

    A console that shows errors from JavaScript and CSS

    Log messages from JavaScript in your web page to the

    console (bye bye "alert debugging") An JavaScript command line (no more "javascript:" in

    the URL bar)

  • 7/29/2019 AJAX Coursework

    52/592

    Development Tools on IE

    Web Developer Toolbar (Firebug for IE)

    >Add-on for IE7 (more similar to Web Dev forFirefox)

    > Included with IE8 (like WebDev + Firebug)

    JavaScript Debugger (free)

    Visual Studio

    HTTP Watch

  • 7/29/2019 AJAX Coursework

    53/592

    11. Ajax:11. Ajax:

    Current Issues & FuturesCurrent Issues & Futures

  • 7/29/2019 AJAX Coursework

    54/592

    Current Issues of Ajax Complexity is increased

    > Server side developers will need to understand thatpresentation logic will be required in the HTML clientpages as well as in the server-side logic

    > Page developers must have JavaScript technologyskills

    Ajax-based applications can be difficultto debug, test, and maintain

    > JavaScript is hard to test - automatic testing is hard

    > Weak modularity in JavaScript - namespace collisionpossible

    > Lack of design patterns or best practice guidelines yet

    Multitude of Toolkits

    C t I f Aj

  • 7/29/2019 AJAX Coursework

    55/592

    Current Issues of Ajax JavaScript technology dependency &

    incompatibility> Must be enabled for applications to function

    > Still some browser incompatibilities

    JavaScript code is visible to a hacker> Poorly designed JavaScript code can invite

    security problem

    Cross Site Ajax

    > Security model only allows XMLHttpRequest tosame domain

    > Script tag hack (JSONP) used, big security risk

  • 7/29/2019 AJAX Coursework

    56/592

    Web 2.0 FrameworksWeb 2.0 Frameworks

    and Toolkitsand Toolkits

    Michael Galpin, eBayMichael Galpin, eBay

    http://fupeg.blogspot.comhttp://fupeg.blogspot.com

  • 7/29/2019 AJAX Coursework

    57/592

    Types of Web 2.0 Toolkit and

    Framework Solutions of Today Clients-side JavaScript Libraries

    Dojo, Prototype, ExtJS, jQuery

    Java World RMI-like remoting via proxy (ex: DWR)

    Java to JavaScript/HTML translator (ex: GWT)

    Web Application Frameworks with AJAXextensions (ex: Ruby on Rails, Wicket)

  • 7/29/2019 AJAX Coursework

    58/592

    Client SideClient Side

    JavaScript LibrariesJavaScript Libraries

    (Examples: Dojo Toolkit,(Examples: Dojo Toolkit,

    Prototype)Prototype)

  • 7/29/2019 AJAX Coursework

    59/592

    Client Side JavaScript Libraries

  • 7/29/2019 AJAX Coursework

    60/592

    Characteristics of Client SideJavaScript Libraries

    Server side technology agnostic

    The server side technology can be Java EE,.Net, PHP, Ruby on Rails, etc.

    You can use them in combination in a

    single app You might want to use widgets and JavaScript

    utilities from multiple sources

    Technical Reasons for using

  • 7/29/2019 AJAX Coursework

    61/592

    Technical Reasons for usingClient-side JavaScript Libraries Handles remote asynch. communication (remoting)

    Hides low-level XMLHttpRequest operation

    Handles browser incompatibilities

    No need to clutter your code with if/else's Handles graceful degradation

    Uses IFrame if the browser does not supportXMLHttpRequest

    Provides page navigation hooks over Ajax

    Back and forward buttons

    Bookmarking

    Technical Reasons for using

  • 7/29/2019 AJAX Coursework

    62/592

    Technical Reasons for usingClient-side JavaScript Libraries

    Provides ready-to-use widgets

    Tree, Calendar, Textfield, Button, Split panes, Fisheye, etc.

    Provides easy-to-use DOM utility

    Easier to use than original DOM APIs

    Provides useful JavaScript utilities

    Example: Table management, Timer, etc

    Provides error handling hook Easier to add error handler

    Provides more flexible event handling

    DOM node based, Function call based, AOP style

  • 7/29/2019 AJAX Coursework

    63/592

    Technical Reasons for using

    Client-side JavaScript Libraries Provides advanced UI features Animation

    Drag and drop Fade out and Fade in

    Generally encourages OO programming

    style Helps you write better JavaScript code

  • 7/29/2019 AJAX Coursework

    64/592

    Business Reasons for using

    Client-side JavaScript Libraries Proven in the market Generally higher quality than your own

    Established developer/user communities Community keeps improving/adding features

    Easy to get help from community forums

    Easy to use It is just a matter of having them in the root

    directory of your Web application or providing

    URL location

    Client side JavaScript Libraries

  • 7/29/2019 AJAX Coursework

    65/592

    Client-side JavaScript Libraries DOJO Toolkit

    Most comprehensive Gaining a leadership in this space

    Major industry support (Sun, IBM)

    http://dojotoolkit.com/

    Prototype

    Most popular

    Used by other toolkit libaries (Rico, Scriptaculous)

    http://prototypejs.org/ Ext JS

    Spin-off from Yahoo UI Library (YUI)

    http://extjs.com/

    Cli t id J S i t Lib i

    http://prototypejs.org/http://prototypejs.org/
  • 7/29/2019 AJAX Coursework

    66/592

    Client-side JavaScript Libraries Script.aculo.us

    Built on Prototype

    Nice set of visual effects and controls

    http://script.aculo.us/

    Rico

    Built on Prototype

    Rich AJAX components and effects

    http://openrico.org/ jQuery

    Fastest growing library

    Innovative DOM/CSS APIs

  • 7/29/2019 AJAX Coursework

    67/592

    Demo: Running VariousDemo: Running VariousClient Side JavaScript ToolkitClient Side JavaScript Toolkit

    DemosDemos

  • 7/29/2019 AJAX Coursework

    68/592

    Dojo ToolkitDojo Toolkit

  • 7/29/2019 AJAX Coursework

    69/592

    Dojo toolkitis made of a

    set oflayeredlibraries

  • 7/29/2019 AJAX Coursework

    70/592

    Demo: Building and RunningDemo: Building and RunningDojo Toolkit ApplicationsDojo Toolkit Applications

  • 7/29/2019 AJAX Coursework

    71/592

    Dojo Demo Scenario Build and run input validation Ajax

    application using Dojo

    Ajax abstraction

    Utility methods

  • 7/29/2019 AJAX Coursework

    72/592

    Prototype

    Ajax abstractions

    Ajax.Updater: uses innerHTML style

    Ajax.Request: data-style

    Ruby like syntax

    Integrated into Rails

    Most popular kit Used by other popular kits

    script.aculo.us

    Rico

  • 7/29/2019 AJAX Coursework

    73/592

    Prototype Demo

  • 7/29/2019 AJAX Coursework

    74/592

    RMI-like RemotingRMI-like Remotingvia Proxyvia Proxy

    (Example: DWR)(Example: DWR)

  • 7/29/2019 AJAX Coursework

    75/592

    RMI-like Remoting via Proxy

    Why DWR?

  • 7/29/2019 AJAX Coursework

    76/592

    y What happens if you have several methods in a

    class on the server that you want to invoke from

    the browser? Each of these methods need to be addressable

    via URI whether you are usingXMLHttpRequestdirectory or client-side only

    toolkit such as Dojo or Prototype You would have to map parameters and return

    values to HTML input form parameters andresponses yourself

    DWR provides a client/server framework thataddresses these problems

    DWR comes with some JavaScript utility functions

  • 7/29/2019 AJAX Coursework

    77/592

    How DWR Works

    DWR Consists of Two Main

  • 7/29/2019 AJAX Coursework

    78/592

    Parts A DWR-runtime-provided Java Servlet running on the server

    that processes incoming DWR requests and sends responsesback to the browser

    org.directwebremoting.servlet.DwrServlet

    This servlet delegates the call to the backend class you

    specify in the dwr.xml configuration file

    Alternatively, use annotations

    @RemoteProxy

    @RemoteMethod

    JavaScript running in the browser that sends requests and candynamically update the webpage

    DWR framework handles XMLHttpRequesthandling

    source: http://getahead.ltd.uk/dwr

    How Does DWR Work?

  • 7/29/2019 AJAX Coursework

    79/592

    DWR generates a matching client-side Javascript class from abackend Java class

    Allows you then to write JavaScript code that looks likeconventional RPC/RMI like code, which is much moreintuitive than writing raw JavaScript code

    The generated JavaScript class handles remoting detailsbetween the browser and the backend server

    Handles asynchronous communication viaXMLHttpRequest - Invokes the callback function in theJavaScript

    You provide the callback function as additional parameter

    DWR converts all the parameters and return valuesbetween client side Javascript and backend Java

  • 7/29/2019 AJAX Coursework

    80/592

    Demo: Building and runningDemo: Building and running

    DWR ApplicationDWR Application

    DWR D S i

  • 7/29/2019 AJAX Coursework

    81/592

    DWR Demo Scenario Build and run Message Board application

    Create Message service class

    Annotate it to expose via DWR

    Use generated JavaScript

    Write JS to load, persist data using DWRgenerated JS

  • 7/29/2019 AJAX Coursework

    82/592

    Java Code To JavaScript/HTMLJava Code To JavaScript/HTML

    Translator: GWTTranslator: GWT

    Wh t i GWT?

  • 7/29/2019 AJAX Coursework

    83/592

    What is GWT? Java software development framework that makes

    writing AJAX applications easy Let you develop and debug AJAX applications in the

    Java language using the Java development tools ofyour choice

    NetBeans or Eclipse

    Provides Java-to-JavaScript compilerand a specialweb browser that helps you debug your GWT

    applications When you deploy your application to production,

    the compiler translates your Java application tobrowser-compliant JavaScript and HTML

    Two Modes of Running GWT

  • 7/29/2019 AJAX Coursework

    84/592

    gApp

    Hosted mode

    Your application is run as Java bytecode within the Java VirtualMachine (JVM)

    You will typically spend most of your development time in hosted

    mode because running in the JVM means you can takeadvantage of Java's debugging facilities

    Web mode

    Your application is run as pure JavaScript and HTML, compiledfrom your original Java source code with the GWT Java-to-JavaScript compiler

    When you deploy your GWT applications to production, youdeploy this JavaScript and HTML to your web servers, so endusers will only see the web mode version of your application

    Why Use Java Programming

  • 7/29/2019 AJAX Coursework

    85/592

    Language for AJAX Development? Static type checking in the Java language boosts

    productivity while reducing errors. Common JavaScript errors (typos, type mismatches) are

    easily caught at compile time rather than by users atruntime.

    Code prompting/completion (through IDE) is useful andwidely available

    Automated Java refactoring is pretty snazzy these days.

    Java-based OO designs are easier to communicate andunderstand, thus making your AJAX code base morecomprehensible with less documentation.

    Java Debuggers >> JavaScript Debuggers

    Why GWT?

  • 7/29/2019 AJAX Coursework

    86/592

    Why GWT? No need to learn/use JavaScript language

    Leverage Java programming knowledge you already

    have

    No need to handle browser incompatibilities and quirks

    GWT handles them for you

    Forward/backward buttons Browser history

    No need to learn/use DOM APIs

    Use Java APIs No need to build commonly used Widgets

    Widgets come with GWT

    Why GWT?

  • 7/29/2019 AJAX Coursework

    87/592

    Why GWT? Leverage various tools of Java programming

    language for writing/debugging/testing

    For example, NetBeans or Eclipse

    JUnit integration

    GWT's direct integration with JUnit lets you unittest both in a debugger and in a browser and youcan even unit test asynchronous RPCs

    Internationalization

    GWT internationalization support provides avariety of techniques to internationalize strings,typed values, and classes

  • 7/29/2019 AJAX Coursework

    88/592

    Demo: Building and runningDemo: Building and runningGWT ApplicationsGWT Applications

  • 7/29/2019 AJAX Coursework

    89/592

    GWT Demo Scenario Build and run GWT Stocks Debug it in Hosted Mode

    Run in Web Mode

  • 7/29/2019 AJAX Coursework

    90/592

    So... What Should I Use?So... What Should I Use?

  • 7/29/2019 AJAX Coursework

    91/592

    The JavaScript

    Programming Language

    Douglas Crockford

    O i

  • 7/29/2019 AJAX Coursework

    92/592

    Overview

    History

    Language

    Advanced Features Platforms

    Standards

    Style

  • 7/29/2019 AJAX Coursework

    93/592

    HistoryHistory

  • 7/29/2019 AJAX Coursework

    94/592

    The World's Most

    Misunderstood

    Programming Language

    Sources of

  • 7/29/2019 AJAX Coursework

    95/592

    Misunderstanding

    The Name

    Mispositioning

    Design Errors Bad Implementations

    The Browser

    Bad Books

    Substandard Standard

    JavaScript is a Functional Language

    History

  • 7/29/2019 AJAX Coursework

    96/592

    History

    1992

    Oak, Gosling at Sun & FirstPerson

    1995

    HotJava

    LiveScript, Eich at Netscape

    1996 JScript at Microsoft

    1998

    ECMAScript

    Not a Web Toy

  • 7/29/2019 AJAX Coursework

    97/592

    Not a Web Toy

    It is a real language

    Small, but sophisticated

    It is not a subset of Java

  • 7/29/2019 AJAX Coursework

    98/592

    Key IdeasKey Ideas

    Key Ideas

  • 7/29/2019 AJAX Coursework

    99/592

    Key Ideas

    Load and go delivery

    Loose typing

    Objects as general containers

    Prototypal inheritance

    Lambda

    Linkage though global variables

  • 7/29/2019 AJAX Coursework

    100/592

    ValuesValues

    Values

  • 7/29/2019 AJAX Coursework

    101/592

    Values

    Numbers

    Strings

    Booleans Objects

    Numbers

  • 7/29/2019 AJAX Coursework

    102/592

    Numbers

    Only one number type

    No integers

    64-bit floating point

    IEEE-754 (aka )

    Does not map well to common

    understanding of arithmetic:

  • 7/29/2019 AJAX Coursework

    103/592

    Special number: Not a Number

    Result of undefined or erroneous

    operations Toxic: any arithmetic operation with

    as an input will have as a

    result

    is not equal to anything,

    including

    Number function

  • 7/29/2019 AJAX Coursework

    104/592

    Number function

    value

    Converts the value into a number.

    It produces if it has a problem.

    Similar to prefix operator.

    parseInt function

  • 7/29/2019 AJAX Coursework

    105/592

    parseInt function value

    Converts the value into a number.

    It stops at the first non-digit character.

    The radix ( ) should be required.

    Math

  • 7/29/2019 AJAX Coursework

    106/592

    Math object is modeled on Java's Math class.

    It containsabsolute value

    integer

    logarithm maximum

    raise to a power

    random number nearest integer

    sine

    square root

    Strings

  • 7/29/2019 AJAX Coursework

    107/592

    Strings Sequence of 0 or more 16-bit

    characters

    UCS-2, not quite UTF-16

    No awareness of surrogate pairs

    No separate character typeCharacters are represented as strings witha length of 1

    Strings are immutable Similar strings are equal ( )

    String literals can use single or doublequotes

    String

  • 7/29/2019 AJAX Coursework

    108/592

    String

    string

    The property determines the

    number of 16-bit characters in a

    string.

    String function

  • 7/29/2019 AJAX Coursework

    109/592

    String function

    value

    Converts value to a string

    String Methods

  • 7/29/2019 AJAX Coursework

    110/592

    String Methods

  • 7/29/2019 AJAX Coursework

    111/592

    Boolean function

  • 7/29/2019 AJAX Coursework

    112/592

    Boolean function

    value

    returns if value is truthy

    returns if value is falsy

    Similar to prefix operator

  • 7/29/2019 AJAX Coursework

    113/592

    A value that isn't anything

  • 7/29/2019 AJAX Coursework

    114/592

    A value that isn't even that

    The default value for variables and

    parameters

    The value of missing members inobjects

    Falsy values

  • 7/29/2019 AJAX Coursework

    115/592

    Falsy values

    empty string)

    All other values (including all objects)

    are truthy.

  • 7/29/2019 AJAX Coursework

    116/592

    Everything Else Is Objects

    Dynamic Objects

  • 7/29/2019 AJAX Coursework

    117/592

    Unification of Object and Hashtable

    produces an empty container of

    name/value pairs

    A name can be any string, a value can be anyvalue except

    members can be accessed with dot notation

    or subscript notation

    No hash nature is visible (no hash codes or

    rehash methods)

    Loosely Typed

  • 7/29/2019 AJAX Coursework

    118/592

    Loosely Typed

    Any of these types can be stored in

    an variable, or passed as a

    parameter to any function

    The language is not "untyped"

    C

  • 7/29/2019 AJAX Coursework

    119/592

    C

    JavaScript is syntactically a C

    family language

    It differs from C mainly in its type

    system, which allows functions to

    be values

    IdentifiersSt t ith l tt

  • 7/29/2019 AJAX Coursework

    120/592

    Starts with a letter or _ or

    Followed by zero or more letters, digits, _ or

    By convention, all variables, parameters,

    members, and function names start with

    lower case

    Except for constructors which start with

    upper case

    Initial _ should be reserved for

    implementations

    should be reserved for machines.

    Reserved Words

  • 7/29/2019 AJAX Coursework

    121/592

    Reserved Words

    abstractboolean byte

    char class constdebugger double

    enum export extendsfinal float

    gotoimplements import int

    interfacelongnativepackage private protected public

    short static super synchronized throws transient volatile

    Comments

  • 7/29/2019 AJAX Coursework

    122/592

    Comments

    Operators

  • 7/29/2019 AJAX Coursework

    123/592

    Arithmetic

    Comparison

    Logical

    Bitwise

    Ternary

  • 7/29/2019 AJAX Coursework

    124/592

    Addition and concatenation

    If both operands are numbers,

    then

    add them

    else

    convert them both to strings

    concatenate them

  • 7/29/2019 AJAX Coursework

    125/592

    Unary operator can convert strings

    to numbers

    Also

    Also

  • 7/29/2019 AJAX Coursework

    126/592

    Division of two integers can produce

    a non-integer result

  • 7/29/2019 AJAX Coursework

    127/592

    Equal and not equal

    These operators can do type

    coercion

    It is better to use and , whichdo not do type coercion.

  • 7/29/2019 AJAX Coursework

    128/592

    The guard operator, aka logical and

    If first operand is truthythen result is second operand

    else result is first operand

    It can be used to avoid null references

    can be written as

  • 7/29/2019 AJAX Coursework

    129/592

    The default operator, aka logical or

    If first operand is truthy

    then result is first operand

    else result is second operand

    It can be used to fill in default values.

    (If is truthy, then is input,

    otherwise set to .)

  • 7/29/2019 AJAX Coursework

    130/592

    Prefix logical notoperator.

    If the operand is truthy, the result is

    . Otherwise, the result is .

    produces booleans.

    Bitwise

  • 7/29/2019 AJAX Coursework

    131/592

    The bitwise operators convert the

    operand to a 32-bit signed integer,and turn the result back into 64-bit

    floating point.

    Statements

  • 7/29/2019 AJAX Coursework

    132/592

    expression

    Break statement

  • 7/29/2019 AJAX Coursework

    133/592

    Statements can have labels.

    Break statements can refer to those

    labels.

    ...

    ...

    For statement

  • 7/29/2019 AJAX Coursework

    134/592

    Iterate through all of the elements

    of an array:

    i i array i

    within the loop,

    iis the index of the current memberarray i is the current element

    For statement

  • 7/29/2019 AJAX Coursework

    135/592

    Iterate through all of the members ofan object:

    name object

    object name

    within the loop,

    nameis the key of current memberobject name is the current value

    Switch statement

  • 7/29/2019 AJAX Coursework

    136/592

    Multiway branch

    The switch value does not need to a

    number. It can be a string.

    The case values can be expressions.

    Switch statement

  • 7/29/2019 AJAX Coursework

    137/592

    expression

    Throw statement

  • 7/29/2019 AJAX Coursework

    138/592

    reason

    exceptionName

    reason

    Try statement

  • 7/29/2019 AJAX Coursework

    139/592

    Try Statement

  • 7/29/2019 AJAX Coursework

    140/592

    The JavaScript implementation canproduce these exception names:

    With statement

  • 7/29/2019 AJAX Coursework

    141/592

    Intended as ashort-hand

    Ambiguous

    Error-prone

    Don't use it

    Function statement

  • 7/29/2019 AJAX Coursework

    142/592

    name parameters

    statements

    Var statement

  • 7/29/2019 AJAX Coursework

    143/592

    Defines variables within a function.

    Types are not specified.

    Initial values are optional.

    Scope

  • 7/29/2019 AJAX Coursework

    144/592

    In JavaScript, blocks do not havescope.

    Only functions have scope.

    Vars defined in a function are notvisible outside of the function.

    Return statement

  • 7/29/2019 AJAX Coursework

    145/592

    expression

    or

    If there is no expression, then the

    return value is .

    Except for constructors, whose

    default return value is .

  • 7/29/2019 AJAX Coursework

    146/592

    ObjectsObjects

  • 7/29/2019 AJAX Coursework

    147/592

    Collections

  • 7/29/2019 AJAX Coursework

    148/592

    An object is an unordered collection ofname/value pairs

    Names are strings

    Values are any type, including otherobjects

    Good for representing records andtrees

  • 7/29/2019 AJAX Coursework

    149/592

    Objects:Objects:

    Object LiteralsObject Literals

    Object Literals

    Object literals are wrapped in

  • 7/29/2019 AJAX Coursework

    150/592

    Object literals are wrapped in

    Names can be names or strings

    Values can be expressions

    separates names and values

    separates pairs

    Object literals can be used anywhere avalue can appear

    Object Literals

  • 7/29/2019 AJAX Coursework

    151/592

    Example: maker Function

  • 7/29/2019 AJAX Coursework

    152/592

    Object Literals

  • 7/29/2019 AJAX Coursework

    153/592

    Object Literals

  • 7/29/2019 AJAX Coursework

    154/592

    Object Literals

  • 7/29/2019 AJAX Coursework

    155/592

    Object Literals

  • 7/29/2019 AJAX Coursework

    156/592

    Obj tObj t

  • 7/29/2019 AJAX Coursework

    157/592

    Objects:Objects:

    Object AugmentationObject Augmentation

    Object Augmentation

  • 7/29/2019 AJAX Coursework

    158/592

    New members can be added to anyobject by simple assignment

    There is no need to define a new

    class

    Obj tObj t

  • 7/29/2019 AJAX Coursework

    159/592

    Objects:Objects:

    LinkageLinkage

    Linkage

  • 7/29/2019 AJAX Coursework

    160/592

    Objects can be created with a secret linkto another object.

    If an attempt to access a name fails, the

    secret linked object will be used.

    The secret link is not used when storing.New members are only added to the

    primary object.

    The o function makes a newempty object with a link to object o.

    Linkage

  • 7/29/2019 AJAX Coursework

    161/592

    Linkage

  • 7/29/2019 AJAX Coursework

    162/592

    Obj tObjects

  • 7/29/2019 AJAX Coursework

    163/592

    Objects:Objects:

    InheritanceInheritance

    Inheritance

  • 7/29/2019 AJAX Coursework

    164/592

    Linkage provides simple inheritance.

    An object can inherit from an older

    object.

    Prototypal Inheritance Some languages have classes,

  • 7/29/2019 AJAX Coursework

    165/592

    g g ,

    methods, constructors, and modules.JavaScript's functions do the work of

    all of those.

    Instead of Classical Inheritance,JavaScript has Prototypal Inheritance.

    It accomplishes the same things, but

    differently.

    It offers greater expressive power.

    But it's different.

    Prototypal Inheritance

  • 7/29/2019 AJAX Coursework

    166/592

    Instead of organizing objects into rigidclasses, new objects can be made that are

    similar to existing objects, and then

    customized.

    Object customization is a lot less work than

    making a class, and less overhead, too.

    One of the keys is the function.

    The other key is functions.

    ObjectsObjects:

  • 7/29/2019 AJAX Coursework

    167/592

    Objects:Objects:

    Object MethodsObject Methods

    Object Methods

  • 7/29/2019 AJAX Coursework

    168/592

    All objects are linked directly or indirectlyto

    All objects inherit some basic methods.

    None of them are very useful. name

    Is the name a true member of this

    object? No method.

    No method.

    Objects:Objects:

  • 7/29/2019 AJAX Coursework

    169/592

    Objects:Objects:

    Object ConstructionObject Construction

    Object Construction

  • 7/29/2019 AJAX Coursework

    170/592

    Make a new empty object

    All three of these expressions have

    exactly the same result:

    is the preferred form.

    Objects:Objects:

  • 7/29/2019 AJAX Coursework

    171/592

    Objects:Objects:

    ReferenceReference

    Reference

  • 7/29/2019 AJAX Coursework

    172/592

    Objects can be passed asarguments to functions, and can be

    returned by functions

    Objects are passed by reference.Objects are not passed by value.

    The operator compares object

    references, not values only if both operands are the same

    object

    Delete

  • 7/29/2019 AJAX Coursework

    173/592

    Members can be removed from anobject with the operator

    myObject name

  • 7/29/2019 AJAX Coursework

    174/592

    ArraysArrays

    Arrays

  • 7/29/2019 AJAX Coursework

    175/592

    inherits from .

    Indexes are converted to strings and

    used as names for retrieving values.

    Very efficient for sparse arrays.

    Not very efficient in most other cases.

    One advantage: No need to provide a

    length or type when creating an array.

  • 7/29/2019 AJAX Coursework

    176/592

    Arrays, unlike objects, have a specialmember.

    It is always 1 larger than the highestinteger subscript.

    It allows use of the traditional

    statement.

    ...

    Array Literals

  • 7/29/2019 AJAX Coursework

    177/592

    An array literal uses It can contain any number of

    expressions, separated by commas

    New items can be appended

    The dot notation should not be usedwith arrays.

    is preferred to .

    Array Methods

  • 7/29/2019 AJAX Coursework

    178/592

    Deleting Elements

  • 7/29/2019 AJAX Coursework

    179/592

    Removes the element, but leaves a

    hole in the numbering.

    Removes the element and

    renumbers all the following

    elements.

    Deleting Elements

  • 7/29/2019 AJAX Coursework

    180/592

    Arrays v Objects

  • 7/29/2019 AJAX Coursework

    181/592

    Use objects when the names arearbitrary strings.

    Use arrays when the names are

    sequential integers.

    Don't get confused by the term

    Associative Array.

    Distinguishing Arrays

  • 7/29/2019 AJAX Coursework

    182/592

    Neither of these work when the value

    comes from a different frame.

    Arrays and Inheritance

  • 7/29/2019 AJAX Coursework

    183/592

    Dont use arrays as prototypes.The object produced this way does not

    have array nature. It will inherit the array's

    values and methods, but not its .

    You can augment an individual array.

    Assign a method to it.

    This works because arrays are objects.

    You can augment all arrays.

    Assign methods to

  • 7/29/2019 AJAX Coursework

    184/592

    FunctionsFunctions

    Functions

  • 7/29/2019 AJAX Coursework

    185/592

    Functions are first-class objects

    Functions can be passed, returned,

    and stored just like any other value

    Functions inherit from and

    can store name/value pairs.

    Function operator

  • 7/29/2019 AJAX Coursework

    186/592

    The function operator takes anoptional name, a parameter list, and

    a block of statements, and returns a

    function object. name parameters

    statements

    A function can appear anywhere

    that an expression can appear.

    lambda

  • 7/29/2019 AJAX Coursework

    187/592

    What JavaScript calls ,other languages call .

    It is a source of enormous

    expressive power.

    Unlike most power-constructs, it is

    secure.

    Function statement

  • 7/29/2019 AJAX Coursework

    188/592

    The function statement is just ashort-hand for a statement with

    a function value.

    expands to

    Inner functions

  • 7/29/2019 AJAX Coursework

    189/592

    Functions do not all have to bedefined at the top level (or left

    edge).

    Functions can be defined inside of

    other functions.

    Scope

  • 7/29/2019 AJAX Coursework

    190/592

    An inner function has access to thevariables and parameters of

    functions that it is contained within.

    This is known as Static Scoping or

    Lexical Scoping.

    Closure

  • 7/29/2019 AJAX Coursework

    191/592

    The scope that an inner functionenjoys continues even after the

    parent functions have returned.

    This is called closure.

    Closure Example

  • 7/29/2019 AJAX Coursework

    192/592

    Function Objects

  • 7/29/2019 AJAX Coursework

    193/592

    Functions are objects, so they cancontain name/value pairs.

    This can serve the same purpose as

    members in other languages.

    Method

  • 7/29/2019 AJAX Coursework

    194/592

    Since functions are values,functions can be stored in objects.

    A function in an object is called a

    method.

    Invocation

  • 7/29/2019 AJAX Coursework

    195/592

    If a function is called with too manyarguments, the extra arguments are

    ignored.

    If a function is called with too fewarguments, the missing values will

    be .

    There is no implicit type checkingon the arguments.

    Invocation

  • 7/29/2019 AJAX Coursework

    196/592

    There are four ways to call a function: Method form

    thisObject methodName arguments

    thisObject methodName arguments

    Function form

    functionObject arguments

    Constructor form

    functionObject arguments Apply form

    functionObject thisObject

    arguments

    Method form

  • 7/29/2019 AJAX Coursework

    197/592

    thisObject methodName arguments

    When a function is called in the

    method form, is set tothisObject, the object containing the

    function.

    This allows methods to have a

    reference to the object of interest.

    Function form

  • 7/29/2019 AJAX Coursework

    198/592

    functionObject arguments When a function is called in the

    function form, is set to the global

    object. That is not very useful.

    It makes it harder to write helper

    functions within a method becausethe helper function does not get

    access to the outer .

    Constructor form

  • 7/29/2019 AJAX Coursework

    199/592

    functionObject arguments

    When a function is called with the

    operator, a new object iscreated and assigned to .

    If there is not an explicit returnvalue, then will be returned.

  • 7/29/2019 AJAX Coursework

    200/592

    thisthis

  • 7/29/2019 AJAX Coursework

    201/592

    is an extraparameter. Its

    value depends on

    the calling form.

    gives

    methods access

    to their objects.

    is bound atinvocation time.

    the new

    objectconstructor

    the objectmethod

    the global

    objectfunction

    Invocation

    form

  • 7/29/2019 AJAX Coursework

    202/592

    argumentsarguments

  • 7/29/2019 AJAX Coursework

    203/592

    When a function is invoked, in additionto its parameters, it also gets a special

    parameter called .

    It contains all of the arguments from

    the invocation.

    It is an array-like object.

    is the number of

    arguments passed.

    Example

  • 7/29/2019 AJAX Coursework

    204/592

  • 7/29/2019 AJAX Coursework

    205/592

    Extending Built-inExtending Built-inTypesTypes

    Augmenting Built-in Types

  • 7/29/2019 AJAX Coursework

    206/592

  • 7/29/2019 AJAX Coursework

    207/592

  • 7/29/2019 AJAX Coursework

    208/592

  • 7/29/2019 AJAX Coursework

    209/592

  • 7/29/2019 AJAX Coursework

    210/592

    eval

    string

  • 7/29/2019 AJAX Coursework

    211/592

    string

    The function compiles and

    executes a string and returns the

    result. It is what the browser uses to convert

    strings into actions.

    It is the most misused feature of thelanguage.

    Function function

  • 7/29/2019 AJAX Coursework

    212/592

    parameters body

    The constructor takes zero or

    more parameter name strings, and a

    body string, and uses the JavaScriptcompiler to produce a function object.

    It should only be used to compile fresh

    source from a server. It is closely related to .

    Built-in Type Wrappers

  • 7/29/2019 AJAX Coursework

    213/592

    Java has and , twoincompatible types which can both

    carry the same value with differing

    levels of efficiency and

    convenience.

    JavaScript copied this pattern to no

    advantage. Avoid it.

    Avoid

    Avoid

    A id

    Confession

  • 7/29/2019 AJAX Coursework

    214/592

    Augmentation

  • 7/29/2019 AJAX Coursework

    215/592

    We can directly modify individualobjects to give them just the

    characteristics we want.

    We can do this without having tocreate classes.

    We can then use our new object as the

    prototype for lots of new objects, eachof which can also be augmented.

    Working with the Grain

  • 7/29/2019 AJAX Coursework

    216/592

    Classical patterns are less effectivethan prototypal patterns or parasitic

    patterns.

    Formal classes are not needed for

    reuse or extension.

  • 7/29/2019 AJAX Coursework

    217/592

    Global ObjectsGlobal Objects

    (global) Object

  • 7/29/2019 AJAX Coursework

    218/592

    The object that dares not speak itsname.

    It is the container for all global

    variables and all built-in objects.

    Sometimes points to it.

    On browsers, is the globalobject.

    Global variables are evil

  • 7/29/2019 AJAX Coursework

    219/592

    Functions within an application canclobber each other.

    Cooperating applications can

    clobber each other.

    Use of the global namespace must

    be minimized.

    Implied Global

  • 7/29/2019 AJAX Coursework

    220/592

    Any var which is not properly declaredis assumed to be global by default.

    This makes it easy for people who do

    not know or care about encapsulationto be productive, but it makes

    applications less reliable.

    JSLint is a tool which helps identifyimplied globals and other weaknesses.

    NamespaceNamespace

  • 7/29/2019 AJAX Coursework

    221/592

    Namespace

  • 7/29/2019 AJAX Coursework

    222/592

    Every object is a separate namespace.

    Use an object to organize your

    variables and functions.

    The Object.

  • 7/29/2019 AJAX Coursework

    223/592

    Example

  • 7/29/2019 AJAX Coursework

    224/592

  • 7/29/2019 AJAX Coursework

    225/592

    TypeType

    Thinking about type

  • 7/29/2019 AJAX Coursework

    226/592

    Trading type-safety for dynamism. JavaScript has no cast operator.

    Reflection is really easy, and usually

    unnecessary.

    Why inheritance?

    Automatic casting

    Code reuse

    Trading brittleness for flexibility.

    Date

  • 7/29/2019 AJAX Coursework

    227/592

    The function is based on Java'sDate class.

    It was not Y2K ready.

    RegExp

  • 7/29/2019 AJAX Coursework

    228/592

    Regular expression pattern matcher Patterns are enclosed in slashes

    Example: a pattern that matches

    regular expressions

    Bizarre notation, difficult to read.

  • 7/29/2019 AJAX Coursework

    229/592

  • 7/29/2019 AJAX Coursework

    230/592

    PlatformsPlatforms

    Platforms

  • 7/29/2019 AJAX Coursework

    231/592

    Browsers

    WSH and Dashboard

    Yahoo!Widgets

    DreamWeaver and Photoshop

    Embedded

  • 7/29/2019 AJAX Coursework

    232/592

    VariantsVariants

    ActionScript

  • 7/29/2019 AJAX Coursework

    233/592

    Empty strings are truthy keywords are case insensitive

    No statement labels

    and return booleans separate operators for strings and

    numbers

    E4X

  • 7/29/2019 AJAX Coursework

    234/592

    Extensions to ECMAScript for XML Proposed by BEA

    Allows literals

    Not compatible with ECMAScript

    Third Edition

    Implemented in ActionScript 3

    Not in IE7

    ECMAScript Fourth Edition

  • 7/29/2019 AJAX Coursework

    235/592

    A very large set of new features arebeing considered.

    Mozilla and Opera are committed.

    It is not clear that Microsoft will

    adopt it.

    No word from Safari yet.

  • 7/29/2019 AJAX Coursework

    236/592

    StyleStyle

    Style

  • 7/29/2019 AJAX Coursework

    237/592

    Programming style isn't aboutpersonal taste.

    It is about rigor in expression.

    It is about clearness in presentation.

    It is about product adaptability and

    longevity.

    Good rules help us to keep the

    quality of our programs high.

    Style and JavaScript

  • 7/29/2019 AJAX Coursework

    238/592

    Style is critically important forJavaScript.

    The dynamic nature of the language

    is considered by some to be "toosoft". Discipline is necessary for

    balance.

    Most of the world's body of

    JavaScript programs is crap.

  • 7/29/2019 AJAX Coursework

    239/592

    Code Conventions for the

    JavaScript Programming

    Language

    Semicolon insertion

  • 7/29/2019 AJAX Coursework

    240/592

    When the compiler sees an error, itattempts to replace a nearby linefeed

    with a semicolon and try again.

    This should alarm you. It can mask errors.

    Always use the full, correct forms,

    including semicolons.

    Line Ending

  • 7/29/2019 AJAX Coursework

    241/592

    Break a line after a punctuator:

    Do not break after a name, string,

    number, or

    Defense against copy/paste errors.

    Comma

  • 7/29/2019 AJAX Coursework

    242/592

    Avoid tricky expressions using thecomma operators.

    Do not use extra commas in arrayliterals.

    Good:

    Bad:

    Required Blocks

  • 7/29/2019 AJAX Coursework

    243/592

    Good:

    Bad:

    Forbidden Blocks

    Blocks do not have scope in JavaScript.

  • 7/29/2019 AJAX Coursework

    244/592

    Blocks should only be used with structured

    statements

    Variables

    D fi ll i bl t th b i i

  • 7/29/2019 AJAX Coursework

    245/592

    Define all variables at the beginningof the function.

    JavaScript does not have blockscope, so their is no advantage in

    declaring variables at the place of

    their first use.

    Expression Statements

    A i b d

  • 7/29/2019 AJAX Coursework

    246/592

    Any expression can be used as astatement. That can mask errors.

    Only assignment expressions and

    invocation expressions should be used

    as statements.

    Good:

    Bad:

    Statement

    A id i f llth h

  • 7/29/2019 AJAX Coursework

    247/592

    Avoid using fallthrough.

    Each clause should explicitly

    or or .

    Assignment Expressions

    D t i t i

  • 7/29/2019 AJAX Coursework

    248/592

    Do not use assignment expressionsin the condition parts of , , or

    .

    It is more likely that

    was intended to be

    Avoid tricky expressions.

    == and !=

    B th t d d t

  • 7/29/2019 AJAX Coursework

    249/592

    Be aware that and do typecoercion.

    Bad

    Good:

    Labels

    U l b l l th

  • 7/29/2019 AJAX Coursework

    250/592

    Use labels only on thesestatements:

    Never use as a label.

    JSLint

    JSLi t h l i th b t

  • 7/29/2019 AJAX Coursework

    251/592

    JSLint can help improve the robustnessand portability of your programs.

    It enforces style rules.

    It can spot some errors that are very

    difficult to find in debugging.

    It can help eliminate implied globals.

    Currently available on the web and as a

    Konfabulator widget.

    Soon, in text editors and Eclipse.

    UHOH!

  • 7/29/2019 AJAX Coursework

    252/592

    Universal Header Onerror Handler

    Inserted into 0.1% of pages Reports on JavaScript errors

    Key Ideas

    L d d d li

  • 7/29/2019 AJAX Coursework

    253/592

    Load and go delivery Loose typing

    Objects as general containers

    Prototypal inheritance

    Lambda

    Linkage though global variables

  • 7/29/2019 AJAX Coursework

    254/592

  • 7/29/2019 AJAX Coursework

    255/592

    Coming Up

    Inheritance

  • 7/29/2019 AJAX Coursework

    256/592

    Modules

    Debugging

    Efficiency

    JSON

    Inheritance

    Inheritance is object oriented

  • 7/29/2019 AJAX Coursework

    257/592

    Inheritance is object-orientedcode reuse.

    Two Schools:

    Classical

    Prototypal

    Classical Inheritance

    Objects are instances of Classes

  • 7/29/2019 AJAX Coursework

    258/592

    Objects are instances of Classes.

    A Class inherits from another

    Class.

    Prototypal Inheritance

    Class free

  • 7/29/2019 AJAX Coursework

    259/592

    Class-free. Objects inherit from objects.

    An object contains a secret link to

    another object.

    Mozilla calls it .

    Prototypal Inheritance

  • 7/29/2019 AJAX Coursework

    260/592

    Prototypal Inheritance

    If an object has a property

  • 7/29/2019 AJAX Coursework

    261/592

    If an object has a property,then the chain will not be

    consulted when accessing

    member .

    Prototypal Inheritance

    If access of a member of

  • 7/29/2019 AJAX Coursework

    262/592

    If access of a member offails, then search for

    the member in .

    If that fails, then search for the

    member in .

    Prototypal Inheritance

    Changes in may be

  • 7/29/2019 AJAX Coursework

    263/592

    Changes in may beimmediately visible in .

    Changes to have no

    effect on .

    Prototypal Inheritance

    can be the prototype

  • 7/29/2019 AJAX Coursework

    264/592

    can be the prototypefor an unlimited number of objects

    which will all inherit its

    properties.

    Prototypal Inheritance

    can be the prototype

  • 7/29/2019 AJAX Coursework

    265/592

    can be the prototypefor an unlimited number of even

    newer objects.

    There is no limit to the length ofthe chain (except common sense).

    Augmentation

    Using the function we can

  • 7/29/2019 AJAX Coursework

    266/592

    Using the function, we canquickly produce new objects that

    have the same state and behavior

    as existing objects.

    We can then augment each of the

    instances by assigning new

    methods and members.

    A prototypal inheritance language

    h ld h t lik th

  • 7/29/2019 AJAX Coursework

    267/592

    should have an operator like the

    function, which makes a new object

    using an existing object as its

    prototype.

    JavaScript instead uses operators that

    look classical, but behave prototypally.

    They tried to have it both ways.

    Three mechanisms:

  • 7/29/2019 AJAX Coursework

    268/592

    Constructorfunctions.

    The operator.

    The member of functions.

    operator

  • 7/29/2019 AJAX Coursework

    269/592

    Constructor

    When functions are designed to be used

    with they are called constructors

  • 7/29/2019 AJAX Coursework

    270/592

    with , they are called constructors.

    Constructors are used to make objects of

    a type or class.

    JavaScript's notation can get a little

    strange because it is trying to look like

    the old familiar classical pattern, while

    also trying to be something reallydifferent.

    operator

    returns a new

  • 7/29/2019 AJAX Coursework

    271/592

    returns a newobject with a link to

    .

    operator

    The function is

  • 7/29/2019 AJAX Coursework

    272/592

    The function ispassed the new object in the

    variable.

    This allows the

    function to customize the new

    object.

    Warning

    The operator is required when

  • 7/29/2019 AJAX Coursework

    273/592

    The operator is required whencalling a Constructor.

    If is omitted, the global object

    is clobbered by the constructor,

    and then the global object is

    returned instead of a new

    instance.

    When a function object is

  • 7/29/2019 AJAX Coursework

    274/592

    When a function object iscreated, it is given a

    member which is

    an object containing a

    member which

    is a reference to the

    function object.

    You can add other members to a

    function's These members

  • 7/29/2019 AJAX Coursework

    275/592

    function s . These members

    will be linked into objects that are

    produced by calling the function with

    the operator.

    This allows for adding constants and

    methods to every object produced,without the objects having to be

    enlarged to contain them.

    method

  • 7/29/2019 AJAX Coursework

    276/592

    Pseudoclassical Inheritance

    Classical inheritance can bei l t d b i i bj t

  • 7/29/2019 AJAX Coursework

    277/592

    Classical inheritance can besimulated by assigning an object

    created by one constructor to the

    prototype member of another.

    This does not work exactly like

    the classical model.

    Example

  • 7/29/2019 AJAX Coursework

    278/592

    Examplestring

    string

  • 7/29/2019 AJAX Coursework

    279/592

    function

    function

    Examplestring

    string

  • 7/29/2019 AJAX Coursework

    280/592

    function

    function

    Examplestring

    string

  • 7/29/2019 AJAX Coursework

    281/592

    function

    function

    Inheritance

    If we replace the originalt t bj t ith i t

  • 7/29/2019 AJAX Coursework

    282/592

    If we replace the originalprototype object with an instance

    of an object of another class, then

    we can inherit another class'sstuff.

    Example

  • 7/29/2019 AJAX Coursework

    283/592

    Examplestring

    string

  • 7/29/2019 AJAX Coursework

    284/592

    function

    function

    Examplestring

    string

  • 7/29/2019 AJAX Coursework

    285/592

    function

    function

    function

    A prototypal inheritance languagesho ld ha e an operator like the

  • 7/29/2019 AJAX Coursework

    286/592

    A prototypal inheritance languageshould have an operator like the

    function, which makes a

    new object using an existingobject as its prototype.

    function

  • 7/29/2019 AJAX Coursework

    287/592

    function

  • 7/29/2019 AJAX Coursework

    288/592

    function

  • 7/29/2019 AJAX Coursework

    289/592

    function

  • 7/29/2019 AJAX Coursework

    290/592

    function

  • 7/29/2019 AJAX Coursework

    291/592

    Public Method

    A Public Method is a function that

    uses to access its object

  • 7/29/2019 AJAX Coursework

    292/592

    uses to access its object.

    A Public Method can be reused

    with many "classes".

    Public Methods

  • 7/29/2019 AJAX Coursework

    293/592

    We can put this function in any object

    at it works.

    Public methods work extremely well

    with prototypal inheritance and with

    pseudoclassical inheritance.

    Singletons

    There is no need to produce a

    class like constructor for an

  • 7/29/2019 AJAX Coursework

    294/592

    class-like constructor for an

    object that will have exactly one

    instance.

    Instead, simply use an object

    literal.

    Singletons

  • 7/29/2019 AJAX Coursework

    295/592

    Singletons

    The methods of a singleton can

    enjoy access to shared private

  • 7/29/2019 AJAX Coursework

    296/592

    enjoy access to shared private

    data and private methods.

    FunctionsFunctions are used as

    Functions

  • 7/29/2019 AJAX Coursework

    297/592

    Functions

    Methods

    Constructors

    Classes

    Modules

    Module Variables defined in a module are

    only visible in the module.

  • 7/29/2019 AJAX Coursework

    298/592

    Functions have scope.

    Variables defined in a function

    only visible in the function.

    Functions can be used a module

    containers.

    Global variables are evil

    Functions within an application

    can clobber each other

  • 7/29/2019 AJAX Coursework

    299/592

    can clobber each other.

    Cooperating applications can

    clobber each other.

    Use of the global namespace

    must be minimized.

    Singletons

  • 7/29/2019 AJAX Coursework

    300/592

    Applications are Singletons

  • 7/29/2019 AJAX Coursework

    301/592

    Privileged Method

    A Privileged Method is a function that

    has access to secret information.

  • 7/29/2019 AJAX Coursework

    302/592

    A Privileged Method has access to

    private variables and private methods.

    A Privileged Method obtains its secretinformation through closure.

    Power Constructor

    Put the singleton module pattern

    in constructor function, and we

  • 7/29/2019 AJAX Coursework

    303/592

    in constructor function, and we

    have a power constructor

    pattern.

    3. Make a new object somehow.

    5. Augment it.

  • 7/29/2019 AJAX Coursework

    304/592

    Power Constructor

    Public methods (from the

    prototype)

  • 7/29/2019 AJAX Coursework

    305/592

    prototype)

    Private variables (var) Private methods (inner functions)

    Privileged methods ( ...)

    No need to use

    Parasitic Inheritance

    A power constructor calls another

    constructor, takes the result,

  • 7/29/2019 AJAX Coursework

    306/592

    constructor, takes the result,

    augments it, and returns it as

    though it did all the work.

  • 7/29/2019 AJAX Coursework

    307/592

    Pseudoclassical Inheritance

  • 7/29/2019 AJAX Coursework

    308/592

    Parasitic Inheritance

  • 7/29/2019 AJAX Coursework

    309/592

    Secrets

  • 7/29/2019 AJAX Coursework

    310/592

    Shared Secrets

  • 7/29/2019 AJAX Coursework

    311/592

    Super Methods

  • 7/29/2019 AJAX Coursework

    312/592

    Inheritance Patterns

    Prototypal Inheritance works

    really well with public methods.

  • 7/29/2019 AJAX Coursework

    313/592

    y p

    Parasitic Inheritance works really

    well with privileged and private

    and public methods.

    Pseudoclassical Inheritance for

    elderly programmers who are oldand set in their ways.

    Working with the Grain

    Pseudoclassical patterns are less

    effective than prototypal patterns

  • 7/29/2019 AJAX Coursework

    314/592

    orparasitic patterns.

    Formal classes are not needed forreuse or extension.

    Be shallow. Deep hierarchies are

    not effective.

    method

    The method causes a

    method on the object to be

  • 7/29/2019 AJAX Coursework

    315/592

    j

    invoked in the future.

    method

  • 7/29/2019 AJAX Coursework

    316/592

    Multiples

    When assigning functions in a

    loop, be aware that all of the

  • 7/29/2019 AJAX Coursework

    317/592

    p,

    functions are bound to the same

    closure.

    This can be avoided by using a

    factor function to produce unique

    bindings.

    Multiples

  • 7/29/2019 AJAX Coursework

    318/592

    Debugging

    As programs get larger and more

    complex, debugging tools are

  • 7/29/2019 AJAX Coursework

    319/592

    p , gg g

    required for efficient

    development.

    Debugging

    IE

    Microsoft Script Debugger

  • 7/29/2019 AJAX Coursework

    320/592

    Office

    Visual Studio

    Web Dev Toolbar: IE7/8

    Mozilla

    Venkman

    Firebug Safari

    Integrated/Optional Dev Tools

    Microsoft Script Debugger

  • 7/29/2019 AJAX Coursework

    321/592

    Microsoft Script Debugger

  • 7/29/2019 AJAX Coursework

    322/592

    Microsoft Script Debugger

  • 7/29/2019 AJAX Coursework

    323/592

    Microsoft Script Debugger

  • 7/29/2019 AJAX Coursework

    324/592

    Venkman

  • 7/29/2019 AJAX Coursework

    325/592

    Venkman

  • 7/29/2019 AJAX Coursework

    326/592

    Venkman

  • 7/29/2019 AJAX Coursework

    327/592

    The statement can be

    used as a programmable

  • 7/29/2019 AJAX Coursework

    328/592

    breakpoint.

    Performance

    Provide a good experience.

  • 7/29/2019 AJAX Coursework

    329/592

    Be respectful of our customer's

    time.

    Hoare's Dictum: Premature

    optimization is the root of all evil.

    Efficiency

    The first priority must always be

    correctness.

  • 7/29/2019 AJAX Coursework

    330/592

    Optimize when necessary.

    Consider algorithmic improvements

    O(n) v O(n log n) v O(n2)

    Watch for limits.

    Coding Efficiency

    Common subexpression removal

  • 7/29/2019 AJAX Coursework

    331/592

    Loop invariant removal

    Before

  • 7/29/2019 AJAX Coursework

    332/592

    After

  • 7/29/2019 AJAX Coursework

    333/592

    Strings

    Concatenation with

    Each operation allocates memory

  • 7/29/2019 AJAX Coursework

    334/592

    Concatenate with array

    The contents of an array are

    concatenated into a single string

    Minification vsObfuscation

    Reduce the amount of source code to

    reduce download time.

    Minification deletes whitespace and

  • 7/29/2019 AJAX Coursework

    335/592

    Minification deletes whitespace and

    comments.

    Obfuscation also changes the names ofthings.

    Obfuscation can introduce bugs.

    Never use tools that cause bugs if youcan avoid it.

    JSON

    JavaScript Object Notation.

    A Data Interchange Format.

  • 7/29/2019 AJAX Coursework

    336/592

    Text-based.

    Light-weight.

    Easy to parse.

    Language Independent. A Subset of ECMA-262

    ECMAScript Third Edition.

    Object

  • 7/29/2019 AJAX Coursework

    337/592

    valuestring

    object

    ,

    Array

  • 7/29/2019 AJAX Coursework

    338/592

    value

    array

    ,

    Value

    string

    value

  • 7/29/2019 AJAX Coursework

    339/592

    number

    string

    object

    array

    String

    string

    Any U N ICO DE character except

    or or control character

    quotation m ark

  • 7/29/2019 AJAX Coursework

    340/592

    reverse solidus

    solidus

    backspace

    form feed

    new line

    carriage return

    horizontal tab

    4 hexadecim al digits

    Number

    number

  • 7/29/2019 AJAX Coursework

    341/592

    number

    digit

    -

    digit

    digit

    digit

    Advanced JavaScript

  • 7/29/2019 AJAX Coursework

    342/592

    Advanced JavaScript

    Douglas Crockford

    JavaScript CookbookJavaScript Cookbook

  • 7/29/2019 AJAX Coursework

    343/592

    Topics

    What is and Why JavaScript? How and Where do you place JavaScript

  • 7/29/2019 AJAX Coursework

    344/592

    code?

    JavaScript language JavaScript functions

    JavaScript events

    JavaScript objects

    JavaScript HTML DOM objects

    What is and WhyWhat is and Why

    JavaScript?JavaScript?

  • 7/29/2019 AJAX Coursework

    345/592

    What is JavaScript?

    Was designed to add interactivity to HTML pages

    Is a scripting language (a scripting language is alightweight programming language)

  • 7/29/2019 AJAX Coursework

    346/592

    lightweight programming language)

    JavaScript code is usually embedded directly into

    HTML pages

    JavaScript is an interpreted language (meansthat scripts execute without preliminary

    compilation)

    What can a JavaScript do? JavaScript gives HTML designers a programmingtool

    JavaScript can put dynamic text into an HTML

    page

    JavaScript can react to events

  • 7/29/2019 AJAX Coursework

    347/592

    JavaScript can react to events

    JavaScript can read and write HTML elements

    JavaScript can be used to validate input data

    JavaScript can be used to detect the visitor'sbrowser

    JavaScript can be used to create cookies

    How and Where Do You PlaceHow and Where Do You Place

    JavaScript Code?JavaScript Code?

  • 7/29/2019 AJAX Coursework

    348/592

    How to put a JavaScript code into anHTML page?

    Use the tag (also use the type attributeto define the scripting language)

  • 7/29/2019 AJAX Coursework

    349/592

    ...

    ...

    Where Do You Place Scripts?

    Scripts can be in the eithersectionorsection

  • 7/29/2019 AJAX Coursework

    350/592

    Convention is to place it in the

    section: Beware of slowness

    ....

    Referencing External JavaScript File

    Scripts can be provided locally or remotelyaccessible JavaScript file using src

  • 7/29/2019 AJAX Coursework

    351/592

    attribute

    JavaScript LanguageJavaScript Language

  • 7/29/2019 AJAX Coursework

    352/592

    JavaScript Variable

    You create a variable with or without the varstatement

    var strname = some value

  • 7/29/2019 AJAX Coursework

    353/592

    var strname some value

    strname = some value

    When you declare a variable within a function, thevariable can only be accessed within that function

    If you declare a variable outside a function, all thefunctions on your page can access it

    The lifetime of these variables starts when they aredeclared, and ends when the page is closed

    JavaScript Popup Boxes

    Alert box

    > User will have to click "OK" to proceed

    > alert("sometext")

  • 7/29/2019 AJAX Coursework

    354/592

    > alert( sometext )

    Confirm box

    > User will have to click either "OK" or "Cancel" toproceed

    > confirm("sometext")

    Prompt box

    > User will have to click either "OK" or "Cancel" toproceed after entering an input value

    > prompt("sometext","defaultvalue")

    JavaScript Language

    Conditional statement> if, if.. else, switch

  • 7/29/2019 AJAX Coursework

    355/592

    Loop

    > for loop, while loop try...catch

    throw

    JavaScript FunctionsJavaScript Functions

    (which behave like(which behave likeJava methods)Java methods)

  • 7/29/2019 AJAX Coursework

    356/592

    Java methods)Java methods)

    JavaScript Funcitons A JavaScript function contains some code that will be

    executed only by an event or by a call to that function> To keep the browser from executing a script as soon as

    the page is loaded you can write your script as a

  • 7/29/2019 AJAX Coursework

    357/592

    the page is loaded, you can write your script as afunction

    You may call a function from anywhere within the page (oreven from other pages if the function is embedded in anexternal .js file).

    Functions are defined either or section

    > As a convention, they are typically defined in the section

    Example: JavaScript Function

    // If alert("Hello world!!") below had not been written within a// function, it would have been executed as soon as the page was loaded.function displaymessage() {

  • 7/29/2019 AJAX Coursework

    358/592

    alert("Hello World!")}

    JavaScript EventsJavaScript Events

  • 7/29/2019 AJAX Coursework

    359/592

    Events & Event Handlers

    Every element on a web page has certain events which

    can trigger invocation of event handlers

    Attributes are inserted into HTML tags to define events

  • 7/29/2019 AJAX Coursework

    360/592

    and event handlers

    Examples of events

    > A mouse click

    > A web page or an image loading

    > Mousing over a hot spot on the web page

    > Selecting an input box in an HTML form

    > Submitting an HTML form

    > A keystroke

    Events

    onabort - Loading of an image is interrupted

    onblur- An element loses focus

    onchange - The content of a field changes

  • 7/29/2019 AJAX Coursework

    361/592

    onchange - The content of a field changes

    onclick - Mouse clicks an object

    ondblclick - Mouse double-clicks an object

    onerror - An error occurs when loading a documentor an image

    onfocus - An element gets focus onkeydown - A keyboard key is pressed

    Events onkeypress - A keyboard key is pressed or held

    down

    onkeyup - A keyboard key is released onload - A page or an image is finished loading

  • 7/29/2019 AJAX Coursework

    362/592

    onmousedown - A mouse button is pressed

    onmousemove - The mouse is moved onmouseout - The mouse is moved off an element

    onmouseover- The mouse is moved over anelement

    onmouseup - A mouse button is released

    Events

    onreset - The reset button is clicked onresize - A window or frame is resized

  • 7/29/2019 AJAX Coursework

    363/592

    onselect - Text is selected

    onsubmit - The submit button is clicked onunload - The user exits the page

    onload & onUnload Events The onloadand onUnloadevents are

    triggered when the user enters or leaves

    the page

    The onload event is often used to check

  • 7/29/2019 AJAX Coursework

    364/592

    the visitor's browser type and browser

    version, and load the proper version of theweb page based on the information

    Both the onload and onUnload events are

    also often used to deal with cookies thatshould be set when a user enters or leavesa page.

    onFocus, onBlur and onChange

    The onFocus, onBlur and onChangeevents are often used in combination withvalidation of form fields

  • 7/29/2019 AJAX Coursework

    365/592

    validation of form fields.

    Example: The checkEmail() function will becalled whenever the user changes thecontent of the field:

    ;

    Example & Demo: onblur

    function upperCase() {d t tEl tB Id("f ") l

  • 7/29/2019 AJAX Coursework

    366/592

    var x=document.getElementById("fname").valuedocument.getElementById("fname").value=x.toUpperCase()

    }

    Enter your name:

    onSubmit The onSubmit event is used to validate ALLform fields before submitting it.

    Example: The checkForm() function will becalled when the user clicks the submitbutton in the form If the field values are not

  • 7/29/2019 AJAX Coursework

    367/592

    button in the form. If the field values are notaccepted, the submit should be cancelled.

    The function checkForm() returns eithertrue orfalse. If it returns true the form willbe submitted, otherwise the submit will be

    cancelled:

    Example & Demo: onSubmit

    function validate() {// return true or false based on validation logic

    }

  • 7/29/2019 AJAX Coursework

    368/592

    Name (max 10 chararcters):


Recommended