SAPX04: HTML5 Foundations for SAP SAPUI5 Development

download SAPX04: HTML5 Foundations for SAP SAPUI5 Development

of 246

Transcript of SAPX04: HTML5 Foundations for SAP SAPUI5 Development

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    1/246

    © 2014 SAP AG. All rights reserved. 1

    SAPX04 HTML5 Foundations for SAP

    SAPUI5 Development

    SAP SAPGUI5Training System: Windows 2008 R2 with latest SAPUI5 component)Collection 95

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    2/246

    © 2014 SAP AG. All rights reserved. 2

    © 2014 SAP AG. All rights reserved.

    No part of this publication may be reproduced or transmitted in any form or for any purposewithout the express permission of SAP AG. The information contained herein may bechanged without prior notice.

    Some software products marketed by SAP AG and its distributors contain proprietarysoftware components of other software vendors.

    Microsoft, Windows, Excel, Outlook, PowerPoint, Silverlight, and Visual Studio areregistered trademarks of Microsoft Corporation.

     Apache Maven, Maven, Apache, the Apache feather logo, and the Apache Maven projectlogos are trademarks of The Apache Software Foundation. This course is not designed toteach candidates MAVEN technology. Existing knowledge of MAVEN is a pre-requisite.

    IBM, DB2, DB2 Universal Database, System i, System i5, System p, System p5, System x,System z, System z10, z10, z/VM, z/OS, OS/390, zEnterprise, PowerVM, Power Architecture, Power Systems, POWER7, POWER6+, POWER6, POWER, PowerHA,pureScale, PowerPC, BladeCenter, System Storage, Storwize, XIV, GPFS, HACMP,RETAIN, DB2 Connect, RACF, Redbooks, OS/2, AIX, Intelligent Miner, WebSphere, Tivoli,Informix, and Smarter Planet are trademarks or registered trademarks of IBM Corporation.

    Linux is the registered trademark of Linus Torvalds in the United States and other countries.

     Adobe, the Adobe logo, Acrobat, PostScript, and Reader are trademarks or registeredtrademarks of Adobe Systems Incorporated in the United States and other countries.

    Oracle and Java are registered trademarks of Oracle and its affiliates.

    UNIX, X/Open, OSF/1, and Motif are registered trademarks of the Open Group.Citrix, ICA, Program Neighborhood, MetaFrame, WinFrame, VideoFrame, and MultiWinare trademarks or registered trademarks of Citrix Systems Inc.

    HTML, XML, XHTML, and W3C are trademarks or registered trademarks of W3C®,World Wide Web Consortium, Massachusetts Institute of Technology.

     Apple, App Store, iBooks, iPad, iPhone, iPhoto, iPod, iTunes, Multi-Touch, Objective-C,Retina, Safari, Siri, and Xcode are trademarks or registered trademarks of Apple Inc.

    IOS is a registered trademark of Cisco Systems Inc.

    RIM, BlackBerry, BBM, BlackBerry Curve, BlackBerry Bold, BlackBerry Pearl, BlackBerryTorch, BlackBerry Storm, BlackBerry Storm2, BlackBerry PlayBook, and BlackBerry App

    World are trademarks or registered trademarks of Research in Motion Limited.

    Google App Engine, Google Apps, Google Checkout, Google Data API, Google Maps,Google Mobile Ads, Google Mobile Updater, Google Mobile, Google Store, Google Sync,Google Updater, Google Voice, Google Mail, Gmail, YouTube, Dalvik and Android aretrademarks or registered trademarks of Google Inc.

    INTERMEC is a registered trademark of Intermec Technologies Corporation.

    Wi-Fi is a registered trademark of Wi-Fi Alliance.

    Bluetooth is a registered trademark of Bluetooth SIG Inc.

    Motorola is a registered t rademark of Motorola Trademark Holdings LLC.

    Computop is a registered t rademark of Computop Wirtschaftsinformatik GmbH.

    SAP, R/3, SAP NetWeaver, Duet, PartnerEdge, ByDesign, SAP BusinessObjects Explorer,StreamWork, SAP HANA, and other SAP products and services mentioned herein as wellas their respective logos are trademarks or registered trademarks of SAP AG in Germanyand other countries.

    Business Objects and the Business Objects logo, BusinessObjects, Crystal Reports, CrystalDecisions, Web Intelligence, Xcelsius, and other Business Objects products and servicesmentioned herein as well as their respective logos are trademarks or registered trademarksof Business Objects Software Ltd. Business Objects is an SAP company.

    Sybase and Adaptive Server, iAnywhere, Sybase 365, SQL Anywhere, and other Sybaseproducts and services mentioned herein as well as their respective logos are trademarks orregistered trademarks of Sybase Inc. Sybase is an SAP company.

    Crossgate, m@gic EDDY, B2B 360°, and B2B 360° Services are registered t rademarksof Crossgate AG in Germany and other countries. Crossgate is an SAP company.

     All other product and service names mentioned are the trademarks of their respectivecompanies. Data contained in this document serves informational purposes only. Nationalproduct specifications may vary.

    The information in this document is proprietary to SAP. No part of this document may bereproduced, copied, or transmitted in any form or for any purpose without the express priorwritten permission of SAP AG.

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    3/246

    © 2014 SAP AG. All rights reserved. 3

    © 2014 SAP AG. Alle Rechte vorbehalten.

    Weitergabe und Vervielfältigung dieser Publikation oder von Teilen daraus sind, zuwelchem Zweck und in welcher Form auch immer, ohne die ausdrückliche schriftlicheGenehmigung durch SAP AG nicht gestattet. In dieser Publikation enthaltene Informationenkönnen ohne vorherige Ankündigung geändert werden.

    Die von SAP AG oder deren Vertriebsfirmen angebotenen Softwareprodukte könnenSoftwarekomponenten auch anderer Softwarehersteller enthalten.

    Microsoft, Windows, Excel, Outlook, PowerPoint, Silverlight und Visual Studio sindeingetragene Marken der Microsoft Corporation.

     Apache Maven, Maven, Apache, the Apache feather logo, and the Apache Maven projectlogos sind eingetragene Marken der Apache Software Foundation.

    IBM, DB2, DB2 Universal Database, System i, System i5, System p, System p5, System x,System z, System z10, z10, z/VM, z/OS, OS/390, zEnterprise, PowerVM, Power Architecture, Power Systems, POWER7, POWER6+, POWER6, POWER, PowerHA,pureScale, PowerPC, BladeCenter, System Storage, Storwize, XIV, GPFS, HACMP,RETAIN, DB2 Connect, RACF, Redbooks, OS/2, AIX, Intelligent Miner, WebSphere, Tivoli,Informix und Smarter Planet sind Marken oder eingetragene Marken der IBM Corporation.

    Linux ist eine eingetragene Marke von Linus Torvalds in den USA und anderen Ländern.

     Adobe, das Adobe-Logo, Acrobat, PostScript und Reader sind Marken oder eingetrageneMarken von Adobe Systems Incorporated in den USA und/oder anderen Ländern.

    Oracle und Java sind eingetragene Marken von Oracle und/oder ihrerTochtergesellschaften.

    UNIX, X/Open, OSF/1 und Motif sind eingetragene Marken der Open Group.

    Citrix, ICA, Program Neighborhood, MetaFrame, WinFrame, VideoFrame und MultiWinsind Marken oder eingetragene Marken von Citrix Systems, Inc.

    HTML, XML, XHTML und W3C sind Marken oder eingetragene Marken des W3C®,World Wide Web Consortium, Massachusetts Institute of Technology.

     Apple, App Store, iBooks, iPad, iPhone, iPhoto, iPod, iTunes, Multi-Touch, Objective-C,Retina, Safari, Siri und Xcode sind Marken oder eingetragene Marken der Apple Inc.

    IOS ist eine eingetragene Marke von Cisco Systems Inc.

    RIM, BlackBerry, BBM, BlackBerry Curve, BlackBerry Bold, BlackBerry Pearl, BlackBerryTorch, BlackBerry Storm, BlackBerry Storm2, BlackBerry PlayBook und BlackBerry AppWorld sind Marken oder eingetragene Marken von Research in Motion Limited.

    Google App Engine, Google Apps, Google Checkout, Google Data API, Google Maps,Google Mobile Ads, Google Mobile Updater, Google Mobile, Google Store, Google Sync,Google Updater, Google Voice, Google Mail, Gmail, YouTube, Dalvik und Android sindMarken oder eingetragene Marken von Google Inc.

    INTERMEC ist eine eingetragene Marke der Intermec Technologies Corporation.

    Wi-Fi ist eine eingetragene Marke der Wi-Fi Alliance.

    Bluetooth ist eine eingetragene Marke von Bluetooth SIG Inc.

    Motorola ist eine eingetragene Marke von Motorola Trademark Holdings, LLC.

    Computop ist eine eingetragene Marke der Computop Wirtschaftsinformatik GmbH.

    SAP, R/3, SAP NetWeaver, Duet, PartnerEdge, ByDesign, SAP BusinessObjects Explorer,StreamWork, SAP HANA und weitere im Text erwähnte SAP-Produkte und -Dienst-leistungen sowie die entsprechenden Logos sind Marken oder eingetragene Marken derSAP AG in Deutschland und anderen Ländern.

    Business Objects und das Business-Objects-Logo, BusinessObjects, Crystal Reports,Crystal Decisions, Web Intelligence, Xcelsius und andere im Text erwähnte Business-Objects-Produkte und Dienstleistungen sowie die entsprechenden Logos sind Markenoder eingetragene Marken der Business Objects Software Ltd. Business Objects ist einUnternehmen der SAP AG.

    Sybase und Adaptive Server, iAnywhere, Sybase 365, SQL Anywhere und weitere im Texterwähnte Sybase-Produkte und -Dienstleistungen sowie die entsprechenden Logos sindMarken oder eingetragene Marken der Sybase Inc. Sybase ist ein Unternehmen derSAP AG.

    Crossgate, m@gic EDDY, B2B 360°, B2B 360° Services sind eingetragene Markender Crossgate AG in Deutschland und anderen Ländern. Crossgate ist ein Unternehmender SAP AG.

     Alle anderen Namen von Produkten und Dienstleistungen sind Marken der jeweiligenFirmen. Die Angaben im Text sind unverbindlich und dienen lediglich zu Informations-zwecken. Produkte können länderspezifische Unterschiede aufweisen.

    Die in dieser Publikation enthaltene Information ist Eigentum der SAP. Weitergabe undVervielfältigung dieser Publikation oder von Teilen daraus sind, zu welchem Zweck undin welcher Form auch immer, nur mit ausdrücklicher schriftlicher Genehmigung durchSAP AG gestattet.

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    4/246

    © 2014 SAP AG. All rights reserved. 4

    Course Topics

    This course covers:

    • HTML5 for SAPUI5 Essentials

    • Creation of HTML and CSS styles

    • JavaScript Development

    •  jQuery Development

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    5/246

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    6/246

    © 2014 SAP AG. All rights reserved. 6

    Course Goals

    This course will prepare you to:• Understand and practice the basics of web programming technique:

    HTML5, CSS3, JavaScript, and jQuery• Describe and understand the basics of security in web programming

    languages

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    7/246© 2014 SAP AG. All rights reserved. 7

    Course Objectives

     After completing this course, you will be able to:

    • Create web pages using basic HTML5 and CSS3

    • Make web pages more lively through JavaScript programming

    • Further improve web pages by using parts of jQuery and jQueryUI

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    8/246© 2014 SAP AG. All rights reserved. 8

    Course Prerequisites

    Required Knowledge (Essential)

    • Basic web skills and experiences such as working with a browser

    • Experience with files and folders, editing source code, using anintegrated development environment

    • Basic knowledge on what programming is about and willingness to

    write code

    Recommended

    • None

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    9/246© 2014 SAP AG. All rights reserved. 9

    Target Audience & Course Duration

    This course is intended for the following audiences:

    • Developers

    • Technology Consultants

    • Product owners and consultants looking for an in-depth overview ofweb development

    Duration: 2 days

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    10/246© 2014 SAP AG. All rights reserved. 10

    Course Content

    Content:

    Unit 1 – Foundations of HTML5 & CSS

    Unit 2 – Foundations of JavaScript

    Unit 3 – Foundations of JQueryUnit 4 – Security

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    11/246© 2014 SAP AG. All rights reserved. 11

    Day 1:

    Welcome & Introductions

    UNIT 1 – Foundations of HTML5 & CSS

    • Lesson 1: HTML5 and CSS3 Essentials

    UNIT 2 – Foundations of JavaScript

    • Lesson 2: Essentials of the JavaScript Language

    Preface

    Course Outline and Schedule

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    12/246© 2014 SAP AG. All rights reserved. 12

    Preface

    Course Outline and Schedule

    Day 2:

    Unit 3 – Foundations of JQuery

    • Lesson 3: JQuery Foundations

    UNIT 4 – Security

    • Lesson 4 - Foundations of HTML, CSS, JavaScript, jQuery Security

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    13/246

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    14/246© 2014 SAP AG. All rights reserved. 14

    Unit 1 – Foundations of HTML5 & CSS:

    Unit Objectives

     After completing this unit, you will be able to:

    • Describe and write HTML5 and CSS code

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    15/246© 2014 SAP AG. All rights reserved. 15

    © SAP 2014/

    Unit 1 – Foundations of HTML5 & CSS:

    Unit Lessons

    Foundations of HTML5 & CSSLesson 1: HTML5 and CSS3 Essentials

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    16/246© 2014 SAP AG. All rights reserved. 16

    Lesson Objectives

     After completing this lesson, you will be able to:

    • Describe and write HTML5 and CSS code

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    17/246

    HTML5 Essentials

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    18/246

    © 2014 SAP AG. All rights reserved. 18

    Web Technologies

    Technology Role ExamplesHTML(HTML5)

    Markup LanguagePage ContentSemantics of the Page

    Headings, ParagraphsSections, Headers, Footers, ArticlesHyperlinks, Buttons

    CSS (CSS3) Annotation Language

    Page Style Appearance of the Page

    Font Style, Size, and Color

    Layout of the Sematic BlocksTransitions, Animations

    JavaScript Programming LanguagePage DynamicsBehavior of the Page

    Popup WindowsEvent Handlers for ButtonsDOM Manipulation AJAX and related Techniques

     jQuery jQueryUI

    JavaScript LibrariesBest Practice SolutionsDomain Specific Language

    Streamlining of Common TasksReusable UI BlocksBrowser Independency

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    19/246

    © 2014 SAP AG. All rights reserved. 19

    What is HTML5? 

    • Next generation of HTML superseding HTML 4.01, XHTML 1.0, XHTML 1.1

    • Standardizes features of the web platform

    • Designed to be cross-platform like its predecessors

    • Defines new tags and markup

    • Describes new JavaScript APIs

    • Deprecates or redefines some so far common elements

    • Supported to a wide extent by the latest versions of Opera, Chrome,

    Firefox, and, to a lesser extent, by IE9

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    20/246

    © 2014 SAP AG. All rights reserved. 20

    What does HTML5 contain?

    Class Examples (Source: http://www.w3.org/html/logo/)Semantics Giving meaning to structure, data driven web

    Offline & Storage Local Storage, Indexed DB, File API

    Device Access Geo Location, Audio/Video Input Access

    Connectivity Web Sockets, Pushing Data from the Client

    Multimedia Audio and video are first class citizens in the HTML5

    3D, Graphics & Effects SVG, Canvas, WebGL, and CSS3 3D

    Performance & Integration Web Workers, XMLHttpRequest2

    CSS3 Wide range of stylization and effects, enhancing the

    web app without sacrificing your semantic structureor performance 

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    21/246

    © 2014 SAP AG. All rights reserved. 21

    Basic HTML 5 Page Template

    Basic HTML 5 Page Template

    • Regarding charset see e.g. http://webdesign.about.com/od/metatags/qt/meta-charset.htm 

    http://webdesign.about.com/od/metatags/qt/meta-charset.htmhttp://webdesign.about.com/od/metatags/qt/meta-charset.htm

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    22/246

    © 2014 SAP AG. All rights reserved. 22

    Know Your Browser

    • Some special URIs (http://en.wikipedia.org/wiki/URI_scheme)

    about: Shows version information and copyright

    information

    about:about Lists all the 'about:' URIs

    about:blank Shows a blank HTML document

    view-source: Shows a web page as code 'in the raw'

    file: Addressing files on local or network file

    systems

    http://en.wikipedia.org/wiki/URI_schemehttp://en.wikipedia.org/wiki/URI_scheme

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    23/246

    © 2014 SAP AG. All rights reserved. 23

    Useful Tools

    • Validate your HTMLhttp://validator.w3.org 

    • Validate your CSS

    • http://jigsaw.w3.org/css-validator  

    • Online version of a complete HTML and CSS Guide

    • http://webkompetenz.wikidot.com/docs:html-handbuch http://www.selfhtml.org 

    •  Try all HTML elements and CSS propertieshttp://www.w3schools.com/html5/default.asp 

    http://validator.w3.org/http://jigsaw.w3.org/css-validatorhttp://webkompetenz.wikidot.com/docs:html-handbuchhttp://www.selfhtml.org/http://www.w3schools.com/html5/default.asphttp://www.w3schools.com/html5/default.asphttp://www.selfhtml.org/http://webkompetenz.wikidot.com/docs:html-handbuchhttp://jigsaw.w3.org/css-validatorhttp://validator.w3.org/

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    24/246

    © 2014 SAP AG. All rights reserved. 24

     Additional Information

    • The W3C maintains an HTML5 landing page

    • http://www.w3.org/html/logo/  

    • The W3C has released a Web Developer's Guide about HTML5http://dev.w3.org/html5/html-author/ 

     All about HTML5 can be read in the specificationhttp://www.w3.org/TR/html5/ 

    On the website http://html5doctor.com you can find a brief discussion on the use

    of any HTML5 element; if you are not sure whether an item was marked upcorrectly, this is the place to look it up

    Microsoft also offers a web site about HTML5http://html5labs.interoperabilitybridges.com/

    http://www.w3.org/html/logo/http://dev.w3.org/html5/html-author/http://www.w3.org/TR/html5/http://html5doctor.com/http://html5labs.interoperabilitybridges.com/http://html5labs.interoperabilitybridges.com/http://html5doctor.com/http://www.w3.org/TR/html5/http://dev.w3.org/html5/html-author/http://www.w3.org/html/logo/

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    25/246

    © 2014 SAP AG. All rights reserved. 25

    Installation of the SAPUI5 Development Environment

    • Get familiar with the structure of the provided training material

    • Download link for the SAPUI5 Developer Studio (Eclipse based)

    • http://vesapui5.dhcp.wdf.sap.corp:1080/trac/sapui5/wiki/Documentation/Tools/download 

    • Recommended is the 64bit version; only if NGAP/BSP repositories are to be used (notrelevant for the training) the 32bit version should be installed

    • MAC users in addition follow the steps from the Installation Guide for ABAP in Eclipse

    • https://wiki.wdf.sap.corp/wiki/display/aie/ABAP+In+Eclipse+on+Mac 

    http://vesapui5.dhcp.wdf.sap.corp:1080/trac/sapui5/wiki/Documentation/Tools/downloadhttps://wiki.wdf.sap.corp/wiki/display/aie/ABAP+In+Eclipse+on+Machttps://wiki.wdf.sap.corp/wiki/display/aie/ABAP+In+Eclipse+on+Machttp://vesapui5.dhcp.wdf.sap.corp:1080/trac/sapui5/wiki/Documentation/Tools/download

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    26/246

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    27/246

    © 2014 SAP AG. All rights reserved. 27

    Lab Environment Setup 2

    • Close the Welcome tab.

    • Go to File  Import.

    • In the Import window thatappears, select General  Existing Projects into Workspaceand then choose Next.

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    28/246

    © 2014 SAP AG. All rights reserved. 28

    Lab Environment Setup 3

    • On the current window, click Select rootdirectory and click Browse…

    • On the next window, navigate to the  Application (N:) drive SAPX04_95\Modul_1_HTML and selectas root directory.

    • Click OK.

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    29/246

    © 2014 SAP AG. All rights reserved. 29

    Lab Environment Setup 4

    • Make sure that allprojects appearing in theProjects area are ticked,and press Finish

    • Verify that your EclipseProject explorer lookssimilar to the following:

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    30/246

    © 2014 SAP AG. All rights reserved. 30

    Total View

    • Expand the“Modul_1_HTML_ Practice” folder toview all directories& files and confirm

    • Note that your startup project files areall in the “exercises”folder

    •  Also note that

    there is asolutions foldercontaining allthe codesolutions

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    31/246

    © 2014 SAP AG. All rights reserved. 31

    Installing the Firebug Add-on in FireFox (1)

    • Launch FireFox andmake sure you are onthe Start Page

    • Click the Add-ons iconat the bottom of thebrowser:

    • This will launch the Add-ons Manager.

    • Use the search field to

    search for the Firebug Add-on.

    • Install it by means of thecorresponding Installbutton:

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    32/246

    © 2014 SAP AG. All rights reserved. 32

    Installing the Firebug Add-on in FireFox (2)

    • Upon installation, note the new tab and the change in status:

    • Close all tabs.

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    33/246

    © 2014 SAP AG. All rights reserved. 33

    Setup for Debugging with FireBug

    • Make sure that your Firebug Console isactivated/enabled by going to FireFox and click theFireBug and set to On for All Web Pages:

    • Enable the Console and click All, as you see in thescreen shot example below:

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    34/246

    © 2014 SAP AG. All rights reserved. 34

    GoalWrite an HTML page showing a push button and analert popup

    Method

    Go to Eclipse

    Expand the exercises folder in your project*

    Use the code fromP02_HTML_Essentials_Exercise_1

    Task

    Copy or create the HTML page skeleton

     Add a push button to the body section

     Add an event handler for button “onclick”Use an alert popup as the event handler

    Test the webpage using FireFox (see next slide toenable FireBug)

    Duration

    15 minutes

    Exercise: Basic HTML Page

    * Note that there isalso a solutions foldercontaining completedcode in case youneed help

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    35/246

    CSS3 Essentials

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    36/246

    © 2014 SAP AG. All rights reserved. 36

    Connecting Stylesheets to HTML

    My Page

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    37/246

    © 2014 SAP AG. All rights reserved. 37

    Basic Selectors

    • Universal Selector

    • The universal selector is an asterisk. It is like a wildcard and matches all elementtypes in the document

    *{}

    • Type Selector

     body, footer, p {}

    • The ID Selector

    • The ID selector works on the value of ID attributes

    #mainHeader {}

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    38/246

    © 2014 SAP AG. All rights reserved. 38

    Basic Selectors

    • Class Selector

    • The class selector matches on the value of class attributes

    paragraph

    .topNavigation {}

    • The Descendant Selector

     A descendant selector of the form "A B" matches when an element B is anarbitrary descendant of some ancestor element A 

    table td {}

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    39/246

    © 2014 SAP AG. All rights reserved. 39

    Property Survey

    /* property: value; */

    font-family: Georgia, Arial;

    font-size: 10px;

    text-transform: uppercase;

    text-decoration: none;font-weight: bold;

     background-color: #FF4400;

    color: #949494;

     border: 2px solid green;

     border-radius: 5px; margin-top: 20px;

     padding-bottom: 5px;

    width: 200px;

    height: 100px;

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    40/246

    © 2014 SAP AG. All rights reserved. 40

    CSS Reset

    • Original CSS Reset from meyerweb

    • http://meyerweb.com/eric/tools/css/reset/  

    • The goal of a reset style sheet is to reduce browser inconsistencies in things like defaultline heights, margins and font sizes of headings, and so on

    • Reset styles quite often appear in CSS frameworks, and the original "meyerweb reset"found its way into Blueprint, (http://www.blueprintcss.org/) among others

    * {

     margin: 0;

     padding: 0;

    }

    http://meyerweb.com/eric/tools/css/reset/http://www.blueprintcss.org/http://www.blueprintcss.org/http://meyerweb.com/eric/tools/css/reset/

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    41/246

    © 2014 SAP AG. All rights reserved. 41

    CSS Box Model

    • Each box has a content area (e.g., text, an image, etc.) and optional surroundingpadding, border, and margin areas

    • The final width (height) of an element is the sum of the margin, padding, borderand the given width (height)

    • http://imagecss.com/ 

    http://imagecss.com/http://imagecss.com/

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    42/246

    © 2014 SAP AG. All rights reserved. 42

    Working with Browser Tools

    • Use function button F12 in browser

    • Firebug plugin for Firefox, no install for Chrome and IE

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    43/246

    © 2014 SAP AG. All rights reserved. 43

    Goal

    Practice the use of basic CSS selectors and properties

    Method

    Return to Exclipse

    Use the code from P03_CSS_Essentials_Exercise_1 in your exercises  folder

    Task

    • Create the HTML document including the  section

    •  Replace _universal, _type, … by appropriate markup

    •Test the webpage

    Duration

    15 minutes

    Exercise: Basic CSS Selectors and Properties

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    44/246

    CSS3 Special Features – Gradients,

    Shadows and Corners

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    45/246

    © 2014 SAP AG. All rights reserved. 45

    Linear Gradients

     background: -moz-linear-gradient(left, blue, white);

     background: -webkit-linear-gradient(left, blue, white);

     background: -moz-linear-gradient(90deg, red, white);

     background: -webkit-linear-gradient(90deg, red, white);

     background: -moz-linear-gradient(top, blue, white 80%, orange);

     background: -webkit-linear-gradient(top, blue, white 80%, orange);

     background: -moz-linear-gradient(left, rgba(255,255,255,0),

    rgba(255,255,255,1)), url(img/bg_landscapeFooter.png);

     background: -webkit-linear-gradient(left, rgba(255,255,255,0),

    rgba(255,255,255,1)), url(img/bg_landscapeFooter.png);

    Linear Gradient

    Linear Gradient with Angle

    Linear Gradient with Color Stops

    Linear Gradient with Transparency

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    46/246

    © 2014 SAP AG. All rights reserved. 46

    Box Shadows

     box-shadow: 8px 8px lightgrey;

     box-shadow: 8px 8px 4px lightgrey;

     box-shadow: 8px 8px 0px 4px lightgrey;

     box-shadow: 8px 8px 4px 4px lightgrey;

     box-shadow: 0px 0px 4px cyan;

     box-shadow: inset 0px 0px 4px cyan;

    #box11:hover {

     box-shadow: 0px 0px 4px cyan;

    }

    Color and Blur

    Spread and Blur

    No Offset and Inset

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    47/246

    © 2014 SAP AG. All rights reserved. 47

    Rounded Corners

     border-radius: 16px;

     border-radius: 20%;

     border-radius: 16px/32px;

     border-radius: 16px 32px;

     border-top-left-radius: 8px;

     border-top-right-radius: 16px;

     border-bottom-right-radius: 24px;

     border-bottom-left-radius: 32px;

    Circular Arcs

    Elliptic Arcs

    Two Corners

    Individual Corners

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    48/246

    © 2014 SAP AG. All rights reserved. 48

    Goal

    Use gradients, shadows, corners

    Method

    Use P03A_CSS_Features_Exercise_1

    Design a form according tothe picture on the right

    Task

    • Add gradient effects

    • Add shadow effects

    • Add rounded corners

    •Test form in browser

    Duration

    30 minutes

    Exercise: Design of a Form

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    49/246

    Using HTML5 Semantic Markup

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    50/246

    © 2014 SAP AG. All rights reserved. 50

    (New) Structural Semantic Tags

    Defines a logical region of a page or a grouping of content

    Defines an article of complete piece of content

    Defines a header region of a page or section•

    Defines a footer region of a page or section

    Defines a navigation region of a page or section

    • Defines secondary or related content 

    •  (block layout) and (inline layout)

    Represents a container with no special meaning used for layout purposes

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    51/246

    © 2014 SAP AG. All rights reserved. 51

    GoalUse the new structural tags und style the resulting page

    Method

    Use the code from P04_HTML_Semantic_Markup_Excerise_1

    Task

    • Create an HTML page

    • Add a header, a footer, and two sections for posts and a sidebar

    • Add horizontal navigation areas to both, the header and the footer

    • Add an article with an aside to the posts section

    • Add a vertical sidebar menu

    • Style the page

    •Test the webpage

    Duration

    30 minutes

    Exercise: Define a Blog Using Semantic Markup

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    52/246

    © 2014 SAP AG. All rights reserved. 52

    Exercise: Define a Blog Using Semantic Markup

    • You tested pageshould appears asfollows:

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    53/246

    User-Friendly Web Forms

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    54/246

    © 2014 SAP AG. All rights reserved. 54

    Survey of Input Types

    • Best supported in Opera and Chrome

    •  

    Groups related elements in a form

    Displays a slider control

    Displays a form field for numbers, often as a spin box

    Displays a form field for dates

    Displays a form field for email addresses

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    55/246

    © 2014 SAP AG. All rights reserved. 55

    Survey of Input Types

    Displays a form field for URLs

    Displays a form field for specifying colors

    Jump to the first field with autofocus.

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    56/246

    © 2014 SAP AG. All rights reserved. 56

    Providing Hints with Placeholder Text

    • Placeholder text provides users with instructions on how they should fill in thefields.

    • HTML5 introduces an aut ocompl ete attribute that tells web browsers that theyshould not attempt to automatically fill in data for the field.

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    57/246

    © 2014 SAP AG. All rights reserved. 57

    Goal

    Use the new HTML5 input features to design a registration form

    Method

    Use the code from P06_HTML_Forms_Exercise_1

    Task• Create an input form with labels and input fields

    • Add first name, last name (both text)

    • Add age (number), email (email), homepage (url)

    • Add Password (password), submit (submit)

    • Use placeholder text and check input validation

    • Validate the entire page using http://validator.w3.org/ 

    •Test the page in a browser

    Duration

    15 minutes

    Exercise: User-Friendly Web Forms

    http://validator.w3.org/http://validator.w3.org/

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    58/246

    © 2014 SAP AG. All rights reserved. 58

    Exercise: User-Friendly Web Forms

    • You tested page should appears as follows:

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    59/246

    Working with HTML5 Custom

    Attributes

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    60/246

    © 2014 SAP AG. All rights reserved. 60

    Custom Attributes (“ data- Attributes” )

    •  Any attribute that starts with "data-" will be treated as a storage area for privatedata (private in the sense that the end user can't see it - it doesn't affect layout orpresentation)

    • This allows you to write valid HTML markup (passing an HTML 5 validator) while,simultaneously, embedding data within your page

    John says: Hello, how are you?

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    61/246

    © 2014 SAP AG. All rights reserved. 61

    JavaScript API

    •  A simple JavaScript API is presented to access these attribute values

    • The . dat aset  property behaves very similarly to the the .attributes property (but

    it only works as a map of key-value pairs)

    var user = document.getElementsByTagName("li")[0];

    var pos = 0, span = user.getElementsByTagName("span")[0];

    var phrases = [

    {name: "city", prefix: "I am from "},

    {name: "food", prefix: "I like to eat "},

    {name: "lang", prefix: "I like to program in "}

    ];

    user.addEventListener( "click", function(){

    var phrase = phrases[ pos++ ];

    // Use the .dataset property

    span.innerHTML = phrase.prefix + user.dataset[ phrase.name ];

    }, false);

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    62/246

    © 2014 SAP AG. All rights reserved. 62

    Goal

    Use custom data attributes to dynamically change a document.

    Method

    Use code from P07_HTML_Attributes_Exercise_1

    Task

    • Create a document, add a paragraph with custom attributes

    • Add button and a div tag

    • Add a button event handler

    • On button click, the custom data shall be written into the div tag

    •Test the page in a browser

    Duration

    15 minutes

    Exercise: Custom Data Attributes

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    63/246

    Styling Tables with HTML5

    Pseudoclasses

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    64/246

    © 2014 SAP AG. All rights reserved. 64

    Pseudoclasses

    • :nth-child(n)

    The :nth-child(n) selector matches every element that is the nth child, regardlessof type, of its parent

    n can be a number, a keyword, or a formula (e.g. 2, even, odd, or 2n+3)

    • :nth-of-type(n)

    The :nth-of-type(n) selector matches every element that is the nth child, of aparticular type, of its parent

    • :last-child

    The :last-child selector matches every element that is the last child of its parent

    •:nth-last-child(n)

    The :nth-last-child(n) selector matches every element that is the nth child,regardless of type, of its parent, counting from the last child

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    65/246

    © 2014 SAP AG. All rights reserved. 65

    Goal

    Use pseudoclasses as CSS selectors to style a table

    Method

    Use code from P08_HTML_Styling_Tables_Exercise_1

    Task

    • Create an HTML document with a table

    • Define table header, body, and footer

    • Style the table header

    • Add a zebra pattern to the table body

    • Style the footer and the last table column

    •Test the page in a browser

    Duration

    15 minutes

    Exercise 1: Styling Tables with Pseudoclasses

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    66/246

    © 2014 SAP AG. All rights reserved. 66

    Exercise 1: Styling Tables with Pseudoclasses

    • You tested page shouldappears as follows:

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    67/246

    © 2014 SAP AG. All rights reserved. 67

    Goal

    Modify the table to make it more interactive

    Method

    Use code from P08_HTML_Styling_Tables_Exercise_2

    If a user moves the mouse over a table row its text shouldbecome more readable and its color should change

    Task

    • Use the :hover selector to modify the text color

    • Use the :hover selector to modify the text decoration

    • Use the :hover selector to modify the background color

    •Test the page in a browser by hovering the mouse over the rows

    Duration

    15 minutes

    Exercise 2: Reacting to Mouse Events

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    68/246

    © 2014 SAP AG. All rights reserved. 68

    Goal

    Using events, enable row deletion

    Method

    Use code from P08_HTML_Styling_Tables_Exercise_3

    If a user clicks on a row it should be removed from the screen

    Task

    • Add event handlers to the table row elements

    •Test the page in a browser by selecting a row (s) to delete

    Duration15 minutes

    Exercise 3: Deletion of Table Rows

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    69/246

    © 2014 SAP AG. All rights reserved. 69

    Exercise 3: Deletion of Table Rows

    • Example of deletions:

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    70/246

    CSS Floats

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    71/246

    © 2014 SAP AG. All rights reserved. 71

    The Definition

    • Defini tion of a float according to the W3C

    “A float is a box that is shifted to the left or right on the current line. The most

    interesting characteristic of a float (or “floated” or “floating” box) is that content

    may flow along its side (or be prohibited from doing so by the “clear” property).

    Content flows down the right side of a left-floated box and down the left side of

    a right-floated box.”

    http://www.w3.org/TR/CSS2/visuren.html#floats 

    • Reference

    http://www.alistapart.com/articles/css-floats-101/ 

    • Tutorial

    http://www.maxdesign.com.au/articles/css-layouts/ 

    CSS Fl

    http://www.w3.org/TR/CSS2/visuren.htmlhttp://www.alistapart.com/articles/css-floats-101/http://www.maxdesign.com.au/articles/css-layouts/http://www.maxdesign.com.au/articles/css-layouts/http://www.alistapart.com/articles/css-floats-101/http://www.w3.org/TR/CSS2/visuren.html

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    72/246

    © 2014 SAP AG. All rights reserved. 72

    CSS Floats

    • How Elements Float

    Elements are floated horizontally, this means that an element can only befloated left or right, not up or down.

     A floated element will move as far to the left or right as it can. Usually thismeans all the way to the left or right of the containing element.

    The elements after the floating element will flow around it.

    The elements before the floating element will not be affected.

    If an image is floated to the right, a following text flows around it, to the left.

    • Turning off Float – Using Clear

    Elements after the floating element will flow around it. To avoid this, use theclear property.

    The clear property specifies which sides of an element other floatingelements are not allowed.

    B ildi F ll CSS L t

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    73/246

    © 2014 SAP AG. All rights reserved. 73

    Building a Full CSS Layout

    Reference: http://www.maxdesign.com.au/articles/process/ 

    B ildi F ll CSS L t

    http://www.maxdesign.com.au/articles/process/http://www.maxdesign.com.au/articles/process/

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    74/246

    © 2014 SAP AG. All rights reserved. 74

    Building a Full CSS Layout

    • Step 1 – Make your layout idea expl ici t

    It could be in the form of a digital mockup, a sketch on paper or an existing site ortemplate

    • Step 2 – Look for the containers

    To position elements on the page, the overall containers need to be establishedLook at your design and work out the main containers on the page

    • Step 3 – Name the containers

    Identify container, header, footer, main navigation, menu, content, …

    • Step 4 – Create the HTML mark up

    Use semantic markup and ID attributes whenever possible

    • Step 5 – Position the overall containers w ith CSS rulesThe positioning of the containers gives the skeleton of the CSS style sheet

    • Step 6 – Style the elements in detail

    Decide on the use of colors, fonts, decorations, images, link behavior, mouse effects, …

    Reference: http://www.maxdesign.com.au/articles/process/ 

    E i 1 CSS Fl t T C l L t

    http://www.maxdesign.com.au/articles/process/http://www.maxdesign.com.au/articles/process/

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    75/246

    © 2014 SAP AG. All rights reserved. 75

    Goal

    Get comfortable with CSS float layouts by writing a page with header,footer, left (floated) column, and right (floated) column

    Method

    Use the code from P10_HTML_CSS_Floats_Exercise_1

    Use screen shot in the following slide to design and build your page

    Task

    • Create the page, refer to the screen shot on the next page

    • Add styles for header, footer, content, and navigation column

    •Test your page in a browser

    Duration

    15 minutes

    Exercise 1: CSS Floats – Two Column Layout

    S Sh t f E i 1

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    76/246

    © 2014 SAP AG. All rights reserved. 76

    Screen Shot for Exercise 1

    E i CSS Fl t Th b il G ll

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    77/246

    © 2014 SAP AG. All rights reserved. 77

    GoalDesign a thumbnail gallery

    Method

    Use the code from P10_HTML_CSS_Floats_Exercise_2

    Use gallery screen shot from the following slideCreate a float layout and style it appropriately 

    Task

    • Create a container for the gallery

    • Create a thumbnail CSS class for the images

    • Add hover effects

    •Test your page in a browser by hovering over the images

    Duration

    15 minutes

    Exercise: CSS Floats – Thumbnail Gallery

    S Sh t f E i 2

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    78/246

    © 2014 SAP AG. All rights reserved. 78

    Screen Shot for Exercise 2

    Unit Summary

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    79/246

    © 2014 SAP AG. All rights reserved. 79

    Unit Summary

     After completing this unit, you should now be able to:

    • Describe and write HTML5 and CSS code

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    80/246

    Foundations of

    JavaScript

    UNIT 2

    Unit 2 Foundations of JavaScript: Unit Objectives

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    81/246

    © 2014 SAP AG. All rights reserved. 81

    Unit 2 – Foundations of JavaScript: Unit Objectives

     After completing this unit, you will be able to:

    • Describe the JavaScript Language

    • Write JavaScript code

    Unit 2 Foundations of JavaScript: Unit Lessons

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    82/246

    © 2014 SAP AG. All rights reserved. 82

    Unit 2 – Foundations of JavaScript: Unit Lessons

    Foundations of JavaScript

    Lesson 2: Essentials of the JavaScript Language

    Lesson Objectives

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    83/246

    © 2014 SAP AG. All rights reserved. 83

    Lesson Objectives

     After completing this lesson, you will be able to:

    • Describe the JavaScript Language

    • Write JavaScript code

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    84/246

    JavaScript Language Basics

    First Example: HTML and JavaScript

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    85/246

    © 2014 SAP AG. All rights reserved. 85

    First Example: HTML and JavaScript

    JavaScript Language Basics

    // Message popupalert("Hello, world!");

    /* Write to console */

    console.log("Hello, world!");

    Script Placement

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    86/246

    © 2014 SAP AG. All rights reserved. 86

    Script Placement

    • Short scripts

    • Place them in the header after the title element and after the CSS includes.

    •  All other scripts should be placed at the end of the body region.

    o The page loading will not be halted while JavaScript is processed

    o HTML elements will be available

    • Do not use the defer Attribute. It only works in IE and Firefox.

    Syntax Issues

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    87/246

    © 2014 SAP AG. All rights reserved. 87

    Syntax Issues

    Identifier

    JavaScript is case sensitive

    The first character of an identifier can be a dollar sign or an underscore and any otherletter, but no number

    Keywords cannot be used as identifiers

    Comments // single line comment

    /* multiline comment

     multiline comment */

    Use a documentation generator

    JSDoc Toolkit

    http://www.jsdoctookit.org 

    YUI Doc

    http://developer.yahoo.com/yui/yuidoc 

    Variables

    http://www.jsdoctookit.org/http://developer.yahoo.com/yui/yuidochttp://developer.yahoo.com/yui/yuidochttp://www.jsdoctookit.org/

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    88/246

    © 2014 SAP AG. All rights reserved. 88

    Variables

    • Use the var keyword

    o If you omit the var keyword, you automatically create a global variable

    o JavaScript is loosely typed, change of type is always possible

    o Multiple definitions are possible

    • Statementso One statement per line

    o  All statements should end with a semicolon

    o Keep your code clean and readable

    Alternatives and Further Developments

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    89/246

    © 2014 SAP AG. All rights reserved. 89

     Alternatives and Further Developments

    Language Developer Remarks

    CoffeeScript Open Source http://coffeescript.org/ 

    Dart Google http://code.google.com/p/dart/ 

    TypeScript Microsoft http://www.typescriptlang.org/ 

    Node Open Source http://nodejs.org/ 

    http://coffeescript.org/http://code.google.com/p/dart/http://www.typescriptlang.org/http://nodejs.org/http://nodejs.org/http://www.typescriptlang.org/http://code.google.com/p/dart/http://coffeescript.org/

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    90/246

    Exercise: Embed JavaScript into an HTML Page

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    91/246

    © 2014 SAP AG. All rights reserved. 91

    GoalLearn how to process JavaScript within an HTML page

    Method

    Use as starter code P21_JS_Language_Basics_Exercise_1

    Task

    • Create an HTML document

    • Insert the  tag at the end of the body

    • Send an alert popup and write some text to the console

    • Display the document in a browser and open the console (F12)

    • Open the script debugger and set a breakpoint

    • Load the page again and see the script stopping

    •Test the page in a browser

    Duration

    10 minutes

    Exercise: Embed JavaScript into an HTML Page

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    92/246

    JavaScript Primitive Data Types

    Comments and Variables

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    93/246

    © 2014 SAP AG. All rights reserved. 93

    Comments and Variables

    // this is a comment

    /* this is ablock comment */

    // variable declaration

    var iMyVariable = 12; 

    // multi variable declarationvar iVar1 = 0, sVar2 = "Hello";

    • There are 2 types of JavaScriptcomments – a single line commentand a block comment

    • By using the keyword „var“ you beginthe declaration of a variable (no type

    is required – since JavaScript isdynamic)

    • To specify more than one variable youcan separate them via comma.

    •  A good practice is to use Hungariannotation for naming variables. You canfind some hints in Wikipedia.

    Basic Data Types

    http://en.wikipedia.org/wiki/Hungarian_notationhttp://en.wikipedia.org/wiki/Hungarian_notation

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    94/246

    © 2014 SAP AG. All rights reserved. 94

    Basic Data Types

    // string var sVar = "Hello World";var sVarAlt = 'Hello World';

    // number (integer && float)var iVar = 1234;

    var fVar = 12.34;

    // boolean var bVar = true;

    // null && undefinedvar vNull = null;var vUndefined = undefined;

    •  A string value can be specified eithervia double or single quotes. In eachcase the surrounding quotes are theleading one and the other quotes canbe used within the string value.

    •  A number can be either an integer ora float. By using the dot you candefine the variable to be a float value.

    •  A boolean value is either true or false.

    • null and undefined are special valueswhereas null is the null object andundefined means explicitly that thevariable is not defined.

    Basic Data Types – String (1)

    http://www.w3schools.com/jsref/jsref_obj_string.asphttp://www.w3schools.com/jsref/jsref_obj_number.asphttp://www.w3schools.com/jsref/jsref_obj_boolean.asphttp://www.w3schools.com/jsref/jsref_obj_boolean.asphttp://www.w3schools.com/jsref/jsref_obj_number.asphttp://www.w3schools.com/jsref/jsref_obj_string.asphttp://www.w3schools.com/jsref/jsref_obj_string.asp

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    95/246

    © 2014 SAP AG. All rights reserved. 95

    Basic Data Types String (1)

    // stringvar sVar = "Hello World";var sVarAlt = 'Hello World';

    // string escapingvar sEsc = "Hello \"World\"";

    // Hello "World"

    // string with a newlinevar sNL = "Hello\nWorld";// Hello// World 

    • Next to using the two different quotesa string can be escaped via usingbackslash to escape the followingcharacter.

    • There are a couple of special

    character representations:• \n newline

    • \r carriage return

    • \t tab

    • \uXXXX unicode character

    Basic Data Types – String (2)

    http://www.w3schools.com/jsref/jsref_obj_string.asp

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    96/246

    © 2014 SAP AG. All rights reserved. 96

    yp g ( )

    // string operationsvar sText = "test string";alert(sText.length); // 11alert(sText.substring(5,7)); // "st"alert(sText.charAt(5)); // "s"alert(sText.indexOf("s")); // 2

    // string separationvar sNames = "Peter,Tim,Frank,Andreas";var aNames = sNames.split(",");

    // "Peter", "Tim", "Frank", "Andreas"

    // string transformation

    alert("JavaScript".toUpperCase()); // JAVASCRIPT

    • The String object provides thefollowing functions:

    • charAt

    • charCodeAt

    • concat

    • fromCharCode• indexOf

    • lastIndexOf

    • match

    • replace

    • search

    • slice

    • split

    • substr• substring

    • toLowerCase

    • toUpperCase

    • valueOf

    Basic Data Types / Object Representation

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    97/246

    © 2014 SAP AG. All rights reserved. 97

    yp / j p

    // string + string objectvar sString = "Hello World";var oString = new String("Hello World");var ooString = new Object("Hello World");

    // number + number objectvar iInt = 1234;var oInt = new Number(1234);var ooInt = new Object(1234);var fFloat = 12.34;var oFloat = new Number(12.34);var ooFloat = new Object(12.34);

    // boolean + boolean objectvar bBool = true;var oBool = new Boolean(true);var ooBool = new Object(true);

    • For each of the 3 basictypes an objectrepresentation exists

    • By calling the constructoryou can create a Stringobject

    • You don’t need to careabout dealing with objects orprimitives since JavaScriptautomatically converts them.

    •  As alternative the objects

    can be created by using theObject constructor. 

    • The difference is that theobjects can be extendedwhereas the primitives not! 

    Exercise: String Processing

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    98/246

    © 2014 SAP AG. All rights reserved. 98

    GoalImplement Caesar's cipher (the shift cipher)

    Method

    Use as starter code P22_JS_Primitive_Data_Types_Exercise_1

    Task• In Caesar's cipher, each character is shifted by a certain offset

    • Consider charCodeAt(), fromCharCode(), and %

    • Use a for loop, e.g. for (var i = 0; i < n; i++) { … }

    • Test the cipher for the alphabet with different offsets 

    Duration

    15 minutes

    g g

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    99/246

    JavaScript Reference Types

    JavaScript Objects

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    100/246

    © 2014 SAP AG. All rights reserved. 100

    p j

    •  Array – Array Object

    • Boolean – Boolean Object (Wrapper)

    • Date – Date Object: Working with Date and Time

    • Function – Function Object (Wrapper)

    • Math – Math Object: Perform Mathematical Tasks

    • Number – Number Object (Wrapper)

    • String – String Object (Wrapper)

    • RegExp – Regular Expression Object: Pattern Matching and Search & Replace

    Objects

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    101/246

    © 2014 SAP AG. All rights reserved. 101

    j

    // object literalvar oObjLiteral = {};

    // objectvar oObject = new Object();

    // dot notationoObject.property;oObject.method([parameter]);

    // square bracket notationoObject["property"];oObject["method"]([parameter]);

    // adding a property to an object

    oObject.newProperty = "Property Value";// adding a new method to an objectoObject.newMethod = function() { /* impl */ };// deleting properties or methodsdelete oObject.newMethod;

    • Objects can be created viaobject literal syntax or byusing the object constructor

    • Properties and/or methodscan be accessed via dot or

    square bracket notation

    • Properties and/or methodscan be added and deleteddynamically during runtime

    Objects (Map)

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    102/246

    © 2014 SAP AG. All rights reserved. 102

    // define the mapvar oMap = {key1: "value1",key2: "value2",key3: "value3"

    };

    alert(oMap["key1"]); // value1 

    alert(oMap["key3"]); // value3 

    • Objects are also often usedas Maps

    • Definition in the Objectliteral syntax with key valuepairs.

    • Values can be accessed viasquare bracket plus thename of the value

    Arrays

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    103/246

    © 2014 SAP AG. All rights reserved. 103

    // array literalvar aArrLiteral = [];var aArrLiteral1 = [1, 2, 3, 4];

    // arrayvar aArray = new Array();var aArray1 = new Array(1, 2, 3, 4);

    // adding valuesaArray.push(5, 6, 7, 8);

    // accessing valuesalert(aArray[0]); // 5

    // joining values

    alert(aArray.join(" - ")); // "5 - 6 - 7 - 8"

    // size of an arrayalert(aArray.length); // 4

    •  Arrays can be created via literalsyntax by using the squarebrackets or by using the Arrayconstructor.

    • Values can be added by usingthe push method

    • Values can be accessed viasquare bracket plus the index ofthe value

    •  An array can be converted intoa string by using the joinmethod and specifying theseparator characters

    • The size can be determined viathe property length

    Functions

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    104/246

    © 2014 SAP AG. All rights reserved. 104

    // function expression (anonymous function)var fnAdd = function(a, b) {return a + b;

    };

    // named function expressionvar fnAdd = function add(a, b) {return a + b;

    };

    // function declarationfunction foo() {// implement function here

    }

    // function object (only for demonstration)var fnAdd = new Function('a, b', 'return a + b');fnAdd(2, 3); // 5

    • Functions are first-class objects • Can be created dynamically

    •  Assignable to variables

    • Can be passed as argumentsto other functions

    • Can have properties and

    methods

    • JavaScript does not have a localscope (block scope). Furthermoreyou only have a “function” scope.

    • Function expressions areassigned to a variable and not

    added to the global or functionscope as the function declaration.

    • Function declarations don’t needa trailing semicolon

    Math

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    105/246

    © 2014 SAP AG. All rights reserved. 105

    // minMath.min(1, 2); // 1

    // maxMath.max(1, 2); // 2

    // PIMath.PI // 3.14…

    // roundMath.round(Math.PI); // 3

    // randomMath.random(); // 0..1

    • The Math object allows you to performmathematical tasks.

    • Math is not a constructor. Allproperties/methods of Math can becalled by using Math as an object,

    without creating it.

    Date

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    106/246

    © 2014 SAP AG. All rights reserved. 106

    // todayvar d = new Date();

    // day of the month (from 1-31)d.getDate();

    // day of the week (from 0-6)d.getDay();

    // month (from 0-11)d.getMonth();

    // year (four digits)d.getFullYear();

    • The Date object is designed to workfor date and time.

    • Date objects are created with newDate().

    Exercise: Reference Types

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    107/246

    © 2014 SAP AG. All rights reserved. 107

    GoalGet familiar with array operations

    Method

    Use the start up code from P23_JS_Reference_Types_Exercise_1

    Task• Write the function insertAfter

    • It takes an array, an element, and a list of new elements

    • The new elements are inserted after the given element

    • If the given element does not occur, the array does not change

    • Consider the use of the array indexOf and splice functions

    Duration

    15 minutes

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    108/246

    JavaScript Operators

    Operators

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    109/246

    © 2014 SAP AG. All rights reserved. 109

    // assignment operator=

    // comparison operators==, !=, >, =, >,

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    110/246

    © 2014 SAP AG. All rights reserved. 110

    alert("1" == 1); // truealert("1" === 1); // falsealert(1 === 1); // true

    // weirdnessalert("1" == true); // truealert("0" == true); // false

    // even weirderalert("" == 0); // true

    • When comparing values using theequality operators (== or !=)JavaScript performs an implicittypecast

    • If you want to avoid this behavior, you

    should use the strict equalityoperators (=== or !==) because thisdoesn‘t perform a typecast beforecomparing

    • When using the equality operator (==)

    there are sometimes amazingresults….

    String Concatenation Operator

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    111/246

    © 2014 SAP AG. All rights reserved. 111

    // number calculation4 + 5; // 9

    // string concatenation"hello" + " world"; // "hello world“

    // when "+" is used with strings and// numbers the result is a string4 + 5 + "five" + 3 + 4; // "9five34“4 + 5 + "five" + (3 + 4); // "9five7" 

    • When using + with numbers, thenumbers are added

    • When using + with strings, the stringsare concatenated

    • When mixing numbers and stringsusing +, the result is always a string.Up to the first string the numbers arestill added, then a concatenationtakes place

    •Using brackets will first carry out thecode within the brackets

    typeof Operator

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    112/246

    © 2014 SAP AG. All rights reserved. 112

    // stringvar sVar = "Hello World";alert(typeof sVar); // string

    // number (integer && float)var iVar = 1234;alert(typeof iVar); // numbervar fVar = 12.34;alert(typeof fVar); // number

    // booleanvar bVar = true;alert(typeof bVar); // boolean

    // null && undefinedvar vNull = null;alert(typeof vNull); // objectvar vUndefined = undefined;

    alert(typeof undefined); // undefined

    // functionvar fnAdd = function(a, b) { return a + b; };alert(typeof fnAdd); // function

    • The typeof-operator allows to checkthe type of a variable.

    • In general you can differ betweenstring, number, boolean, object,function and undefined

    • Strange behavior - be aware:

    • user-defined objects are typeof object

    • built-in type Array is typeof object

    • the null value is typeof object

    typeof Operator (does not work for objects!)

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    113/246

    © 2014 SAP AG. All rights reserved. 113

    // stringvar oString = new String("Hello World“);alert(typeof oString ); // objectalert(oString.constructor === String); // true

    // number (integer && float)var oInt = new Number(1234);alert(typeof oInt ); // objectalert(oInt.constructor === Number); // truevar oFloat = new Number(12.34);alert(typeof oFloat); // objectalert(oFloat.constructor === Number); // true

    // booleanvar oBool = new Boolean(true);

    alert(typeof oBool); // objectalert(oBool.constructor === Boolean); // true 

    • The type of objects can bechecked by utilizing theconstructor property.

    • The constructor propertycontains the reference to

    the constructor functionwhich can be used tocheck the type of anobject.

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    114/246

    JavaScript Statements

    if … else … condition

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    115/246

    © 2014 SAP AG. All rights reserved. 115

    // defaultif (condition) {

    // impl when true;} else {

    // impl when false;}

    // checking defined objectsif (object) {// do something

    }

    • The condition can be either a booleanvariable or you can also checkingobjects for being defined and having acorrect value.

    • Not using the curly brackets is bad

    style and is a common source forissues. You should acquire the habitto always make use of the curlybrackets.

    switch… command

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    116/246

    © 2014 SAP AG. All rights reserved. 116

    switch (var) {case value1:

    // impl;break;

    case value2:// impl;

    break;default:

    // impl;}

    • Each case of the switch commandshould end with a break statement.Otherwise the following case will alsobe executed.

    • The default case is executed when no

    other case matches.

    while… loop

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    117/246

    © 2014 SAP AG. All rights reserved. 117

    while (condition) {// loop impl

    }

    • The while loop executes its codinguntil the condition is true. Thecondition will be checked before theexecution of the code.

    do… while… loop

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    118/246

    © 2014 SAP AG. All rights reserved. 118

    do {// loop impl

    } while (condition);

    • The do while loop executes its codinguntil the condition is true. Thecondition will be checked after theexecution of the code.

    for… loop

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    119/246

    © 2014 SAP AG. All rights reserved. 119

    for (expr; cond; it) {// loop impl

    }

    • The for loop will be executed until thecondition (cond) is true. The startexpression (expr) will be definedbefore the execution of the for loopand the iteration expression (it) isexecution after each execution of the

    coding.

    for… in… loop

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    120/246

    © 2014 SAP AG. All rights reserved. 120

    var oObject = {key1: "value1",key2: "value2"

    };for (var sKey in oObject) {

    var oProp = oObject[sKey];}

    var aArray = ["value1", "value2"

    ];for (var iIndex in aArray) {

    var oValue = aArray[iIndex];

    }

    • With the for in loop you can iterateover each property of an object. Ineach loop cycle the name (key) of theproperty is assigned to the definedvariable.

    • You can also iterate over the entriesof an array. In each loop cycle theindex of the next value of the array isassigned to the variable.

    • Be aware:

    • The basic Object type can be extendedwith additional properties. This will adunexpected values to the for in loop(also Arrays are affected since they areObjects).

    • No guarantee for the order of properties

    looping – doing it right!

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    121/246

    © 2014 SAP AG. All rights reserved. 121

    var oObject = {key1: "value1",key2: "value2"

    };for (var sKey in oObject) {

    if (oObject.hasOwnProperty(sKey)) {var oProp = oObject[sKey];

    }}

    var aArray = ["value1", "value2"

    ];

    for (var i = 0, l = aArray.length; i < l; i++) {var oValue = aArray[iIndex];}

    • Use for in loop toiterate over theproperties of anobject. To prevent sideeffects just add thefunction hasOwnProperty

    to make sure that theproperty is defined onthe current object.

    • For Arrays just makeuse of the standard for

    loop to make sure toget no side effects.

    Conditional Assignment ( ? : )

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    122/246

    © 2014 SAP AG. All rights reserved. 122

    var nCount = 0;var sText = "test";

    if (sText=="test") {nCount += 1;

    } else {nCount -= 1;

    }

    alert(nCount); // 1

    // this is the same but shorternCount = (sText == "test") ? nCount + 1 : nCount - 1;alert(nCount); // 2

    • The semantic behindthe conditionalassignment is:

    • condition ?value_if_true :value_if_false 

    • Do not nestconditionalassignments sincethis makes the codenot readable anymore.

    Exercise: Statements

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    123/246

    © 2014 SAP AG. All rights reserved. 123

    GoalUse a for … in … loop to copy the properties of an object

    Method

    Use the start up code from P25_JS_Statements_Exercise_1

    Task• Create an object literal

    • Add some properties (remember concept “object as a map”)

    • Use a for … in … loop to copy the properties into an array

    • Output the array

    Duration

    15 minutes

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    124/246

    JavaScript Variables and Scope

    Variables and Scope

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    125/246

    © 2014 SAP AG. All rights reserved. 125

    Characteristics

    • Do not create a variable inside a function without the keyword var Otherwise, it is a global variable

    • If you copy an object, you copy only the reference on it

    You also cannot pass an object by value, only by reference

    • Keep an eye on the execution contextIf a variable is created, it is also accessible in a function which has beencreated in the same context (used especially when creating closures)

    • JavaScript does not have block-level scopeIt only supports global and function scopeBe aware of variable hoisting

    Exercise: Variables and Scope – Closure

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    126/246

    © 2014 SAP AG. All rights reserved. 126

    GoalGet familiar with the concept of a “closure”

    Method

    Use the starter code from P26_JS_Variables_Scope_Exercise_1

    Task• Write a (outer) function that returns a (inner) function

    • The outer function takes one argument, say n

    • The returned inner function also takes one argument, say x

    • The inner function returns x+n

    • Define several of those “adders” and test them 

    Duration

    15 minutes

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    127/246

    JavaScript Error Handling

    Reasons for Throwing JavaScript Errors

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    128/246

    © 2014 SAP AG. All rights reserved. 128

    • If programs fail silently, it can take long time to notice an issue

    • Throwing errors leads to easier debugging and code maintenance

    • Since JavaScript native errors are quite unspecific, consider the use of userdefined error objects

    • Compared to other languages, tool support, e.g. debuggers, in JavaScript is stillevolving – thus support for error detection in the code is even more important

    How to Throw Errors

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    129/246

    © 2014 SAP AG. All rights reserved. 129

    • Throw an error by using the throw operator and providing an object to throw

    •  Any type of object can be thrown; an Error  object is the most typical to use

    • Browsers display errors in their specific ways

    •Often some console window is used

    throw new Error("Something bad happened.");

    Throwing an Error String

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    130/246

    © 2014 SAP AG. All rights reserved. 130

    Throwing an Error Object

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    131/246

    © 2014 SAP AG. All rights reserved. 131

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    132/246

    Best Practice

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    133/246

    © 2014 SAP AG. All rights reserved. 133

    • Provide the text to be displayed to the Error  constructor

    • Include the function name and why the function failed

    When to Throw Errors

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    134/246

    © 2014 SAP AG. All rights reserved. 134

    • JavaScript does not have argument or type checking

    • Do not implement this for every function!

    • The key is proper organization of the code: Modularization and layering

    The use of internal or private functions is known and thus they should be tested duringdevelopment

    Functions making up the public interface or API should implement arguments checkingand signal wrong use to the caller

     Avoid throwing errors from deep below the call stack, since this forces your user to

    understand the details of your implementation

    Consider to catch those errors in the public interface and eventually throw them againmore digestible to the caller

    This is especially important for library design

    ECMA-262 Error Object Types

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    135/246

    © 2014 SAP AG. All rights reserved. 135

    Type Description

    Error Base type for all errors; never actually thrown by the engine

    EvalError Thrown when an error occurs during execution of code viaeval()

    RangeError Thrown when a number is outside the bounds of its range; forexample, trying to create an array with -20 items (new

     Array(-20)); these occur rarely during normal executionReferenceError Thrown when an object is expected but not available, for

    instance, trying to call a method on a null reference

    SyntaxError Thrown when the code passed into eval() has a syntax error

    TypeError Thrown when a variable is of an unexpected type; for example,new 10 or "prop" in true 

    URIError Thrown when an incorrectly formatted URI string is passed intoencodeURI, encodeURIComponent, decodeURI, ordecodeURIComponent 

    Error Handling

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    136/246

    © 2014 SAP AG. All rights reserved. 136

    • The mechanism of error handling: The try …catch statement 

    try {

    someFunction();

    } catch (error){

    if (error instanceof TypeError){// Handle type error

    } else if (error instanceof ReferenceError){

    // Handle reference error

    } else {

    // Handle all other errors

    }

    }

    Best Practice when Throwing and Catching Errors

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    137/246

    © 2014 SAP AG. All rights reserved. 137

    • Do not leave catch clauses empty, since this does not handle errors but justmasks them

    • On the contrary, do not expose each and every technical exception to the user

    • Target design:

    Lower, technical layers throw exceptions

    Higher, application layers handle exceptions

    • In the application context you can often decide how to deal with the errorsituation, e.g. whether to signal it to the user or to take different approach to

    complete the task

    User Defined Error Type

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    138/246

    © 2014 SAP AG. All rights reserved. 138

     Advantages of User Defined Errors

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    139/246

    © 2014 SAP AG. All rights reserved. 139

    function MyError(message) {

    this.message = message;}

     MyError.prototype = new Error();

    try {

    throw new MyError("Hello, world!");

    } catch (error) {

    if ( error instanceof MyError) {

    console.log(error.name + ' says "' + error.message + '".');} else {

    console.log("Something else happened.");

    }

    }

    • React to the difference between own errors and browser errors

    • Error message will be displayed in the browser’s normal error handlingmechanism

    • Browser attaches extra information to the error objects when they are thrown

    Debugging Techniques

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    140/246

    © 2014 SAP AG. All rights reserved. 140

    • Use the consoleconsol e. l og( "Er r or ") ;

    • Use a custom di v container

    var debugI nf o = document . get El ement ByI d( "debugI nf o") ;

    debugI nf o. i nner HTML = " … ";

    Exercise: JavaScript Error Handling

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    141/246

    © 2014 SAP AG. All rights reserved. 141

    GoalGet familiar with common error situations

    Method

    Use the starter code from P27_JS_Error_Handling_Exercise_1

    Task• Replace '___' by proper code to handle the errors situations

    • Replace 'e.name' by more descriptive member of the error object

    • Write equivalent code using instanceof

    Duration

    15 minutes

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    142/246

    JavaScript DOM Manipulation

    Selecting Elements

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    143/246

    © 2014 SAP AG. All rights reserved. 143

    • By IDgetElementById("col1");

    • By name

    getElementsByName

    • By tag name

    getElementsByTagName

    • HTML5 method

    var selected = document.querySelector(".selected");

    Tree Nodes

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    144/246

    © 2014 SAP AG. All rights reserved. 144

    • Create an Attr ibutvar attr = document.createAttribute("align");

    attr.nodeValue = "right";

    var el = document.getElementsByTagName("h2")[0];

    el.setAttributeNode(attr);

    • Create a Text Node

    var txt = document.createTextNode(document.lastModified);

    var old = document.createTextNode("Last update: ");

    document.getElementById("date").appendChild(old);

    document.getElementById("date").appendChild(txt);

    • Create an Element

    var el = document.createElement("h1");

    var txt = document.createTextNode("Content");

    el.appendChild(txt);

    var content_section = document.getElementById("col1");

    content_section.appendChild(el);  

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    145/246

    JavaScript Events

    Handler Types

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    146/246

    © 2014 SAP AG. All rights reserved. 146

    • HTML Event Handlersonclick = alert('hello);

    • DOM Level 0 Event Handlers

    el.onclick = function() { … };

    • DOM Level 2 Event Handlers

    el.addEventListener("click", , false);

    Multiple event handler can be added

    • Internet Explorer

    el.attachEvent("onclick", function(){ … });

    Cross Browser Solution

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    147/246

    © 2014 SAP AG. All rights reserved. 147

    var EventManager = {addHandler: function(element, type, handler){

    if (element.addEventListener){

    element.addEventListener(type, handler, false);

    } else if (element.attachEvent){

    element.attachEvent("on" + type, handler);

    } else {

    element["on" + type] = handler;)};

    EventManager.addHandler(el,"click",handler);

    Event Bubbling – Definition

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    148/246

    © 2014 SAP AG. All rights reserved. 148

    • The concept of event bubbling was introduced to deal with situations where asingle event, such as a mouse click, may be handled by two or more eventhandlers defined at different levels of the Document Object Model (DOM)hierarchy

    • If this is the case, the event bubbling process starts by executing the eventhandler defined for individual elements at the lowest level (e.g. individualhyperlinks, buttons, table cells etc.)

    • From there, the event bubbles up to the containing elements (e.g. a table or aform with its own event handler), then up to even higher-level elements (e.g. theBODY element of the page)

    • Finally, the event ends up being handled at the highest level in the DOMhierarchy, the document element itself (provided that your document has its ownevent handler)

    Event Bubbling – Example

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    149/246

    © 2014 SAP AG. All rights reserved. 149

    • Event bubbling is the default

    • If you want to suppress it, set the event property cancelBubble to true

    var cnt3 = document.getElementById('container3');

    cnt3.addEventListener('click', function(event) {

    console.log("Event handler for container 3 (table row)");

    event.cancelBubble = true;

    });

    Event Propagation – Definit ion

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    150/246

    © 2014 SAP AG. All rights reserved. 150

    • The term event propagation is often used as a synonym of event bubbling• However, strictly speaking, event propagation is a wider term: it includes not only

    event bubbling but also event capturing

    • Event capturing is the opposite of bubbling (events are handled at higher levelsfirst, then sink down to individual elements at lower levels)

    • Event capturing is supported in fewer browsers and rarely used; notably, InternetExplorer prior to version 9.0 does not support event capturing

    Exercise: JavaScript Event Handling

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    151/246

    © 2014 SAP AG. All rights reserved. 151

    Goal

    Get familiar with adding event handlers to push buttons

    Method

    Use code from P29_JS_Events_Exercise_1.html

    Task• Add an HTML event handler to the first button

    • Add a DOM Level 0 event handler to the second button

    • Add two DOM Level 2 event listeners to the third button

    • Easy reaction is to send an alert popup or to change “innerHTML”

    •Test

    Duration

    15 minutes

    Resulting page withlast button changedafter click event

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    152/246

    Object Oriented Programming

    Constructor Functions

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    153/246

    © 2014 SAP AG. All rights reserved. 153

    // creation via functionsvar myEmployee = new Employee();

    // constructor function executionfunction Employee() {

    // create a new object via literal

    // var this = {};

    // add properties and methods to the// objectthis.property = "propValue";this.method = function () {};

    // implicitly return this instance// return this;

    }

    • If a function is used to create objectsthe function serves as a constructorand is called constructor function. Byconvention those functions start withan upper case character.

    • If you call a constructor function via“new” the following happens:

    •  An empty object will be created which isreferenced via the variable this. Theprototype of the function is inherited.

    • Properties and Methods are assigned to

    the object via this.• The newly created object will be

    implicitly returned at the end of theconstructor function.

    Object Properties

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    154/246

    © 2014 SAP AG. All rights reserved. 154

    function Employee() {this.property = "propValue";this.method = function () {};

    }

    var myEmployee1 = new Employee();var myEmployee2 = new Employee();

    myEmployee1.myAttr = "test";myEmployee2.myFunc = function() {};

    alert(myEmployee1.property);// "propValue"alert(myEmployee2.property);// "propValue"

    alert(myEmployee1.myAttr); // "test"alert(myEmployee2.myAttr); // "undefined"

    alert(myEmployee1.myFunc); // "undefined"alert(myEmployee2.myFunc); // "function"

    • Properties and methods can be addedto an object at any time in theprogram

    • Properties or methods which areadded to an object are only available

    for the particular object not the otherobjects of the same origin.

    • If properties or methods are added inthe constructor function they will beavailable on each object created viathis function.

    No Classes, but Prototypes

  • 8/15/2019 SAPX04: HTML5 Foundations for SAP SAPUI5 Development

    155/246

    © 2014 SAP AG. All rights reserved. 155

    • JavaScript has no classes which is strange for developers of other languages• Objects can be created on demand and properties and methods will be added

    as required.

    • New objects are not empty. It contains some properties and methods but theyare not “own” properties or methods.

    •  A prototype is an object from which other objects inherit properties.

    • Every object has a prototype by default. Since prototypes are themselvesobjects, every prototype has a prototype too (There is only one e