Vous êtes sur la page 1sur 113

Web Programming using

SAP UI5
Bogdan MIHAI
Research Scientist, Performance and Insight Optimization
September 30th, October 2nd, 4th, 7th and 9th, 2013 Internal
Web Programming using SAP UI5
From zero to hero in just 5 days

Bogdan MIHAI (bogdan-eugen.mihai@sap.com)


Performance and Insight Optimization
September 30th, October 2nd, 4th, 7th and 9th, 2013
Agenda – part 1
Day 1 – September 30th
 Introduction
 HTML
 HTTP
 JavaScript
 Quiz
Day 2 – October 2nd
 Introduction
 Typical Web Architecture, Communication Across The Internet
 Web Services, RESTful Services
 SAP UI5 Overview
 SAP UI5 Programming + DEMO
 Control API + DEMO
 Quiz

© 2013 SAP AG. All rights reserved. Internal 3


Agenda – part 2
Day 3 – October 4th
 Introduction
 MVC Concepts
 Fragments
 Localization
 JSON Model Binding + DEMO
 OData Model Binding + DEMO
 Quiz
Day 4 – October 7th
 Introduction
 Charts
 Using external JavaScript libraries + DEMO
 Modularization and Resource Handling
 Styling and Theming + DEMO

© 2013 SAP AG. All rights reserved. Internal 4


Agenda – part 3
Day 5 – October 9th
 Custom Controls + DEMO
 Security Concepts + DEMO
 DEMO: Building A Sample Web Application From Scratch
 Final Quiz
 Feedback

© 2013 SAP AG. All rights reserved. Internal 5


Web Programming using
SAP UI5
Day 1 – September 30th
1. Introduction
How it all began?
1. Introduction – World Wide Web (WWW)

World Wide Web (WWW)

• Developed between March 1989 and December 1990 by Tim Berners-Lee of CERN

• A set of documents (pages) connected together with hyperlinks

• It is distributed on multiple physical computers

• It includes a reference page (home page)

• It is using a client-server architecture: the pages are hosted on servers and visited by clients

© 2013 SAP AG. All rights reserved. Internal 8


1. Introduction – Client-Server Interaction

Client-Server Interaction
1. The end-user enters an URL into the browser address box (www.sap.com)

2. The browser finds out the address (IP address) of the requested domain, by “asking” a DNS server

3. The DNS server replies with the IP address (155.56.74.65)

4. The browser opens a TCP connection on the specified port (default is 80) to the web server

5. The browser sends a HTTP Get command to the web server requesting the web page

6. The web server sends the web page to the browser

7. The TCP connection is closed*

8. The browser “reads” the web page

9. The browser displays the web page to the end-user

© 2013 SAP AG. All rights reserved. Internal 9


1. Introduction - Technologies

Three essential technologies

1. A system of globally unique identifiers for web documents – URL (Uniform Resource Locator)

2. A document language – HTML (Hypertext Markup Language)


• It includes a document model – DOM (Document Object Model)

3. A communication protocol – HTTP (Hypertext Transfer Protocol)

Two more additions

1. A way of making web documents beautiful – CSS (Cascade Styling Sheets)

2. The de facto language of the Internet – ECMAScript, also known as JavaScript

© 2013 SAP AG. All rights reserved. Internal 10


1. Introduction – Uniform Resource Locator (URL)

Uniform Resource Locator (URL)

Pattern: scheme://host[:port#]/path/…/[;url-params][?query-string][#anchor]
 scheme – the protocol (http, ftp, file, news, mailto, telnet, etc.)

 host – the IP address or the domain name

 port – the TCP connection port (the default value is 80)

 path – the path to the requested document

 url-parameters – session identifying (not safe – usually not used)

 query-string – values of the html document

 anchor – reference to a place in the html document

Example: http://www54.sap.com/search/search-results.html?Query=ui5

© 2013 SAP AG. All rights reserved. Internal 11


2. HTML
Not a real programming language!
2. HTML – Overview

The Hypertext Markup Language


 Developed by World Wide Web Consortium (W3C)

 Most popular version: 4.0.1, published in December 1999.

 Latest version: 5, first published as a draft in January 2008.

 XHTML – different language that uses HTML 4.0.1 as XML

 It can embed CSS or JavaScript resources

 Three basic entities

– Tags, usually they come in pairs (start tag, and end tag)

– Attributes

– Attribute values

 The tags values represent the actual document content

© 2013 SAP AG. All rights reserved. Internal 13


2. HTML – Common tags
Common tags
Tag Description

<html> </html> Defines a html document


<head> </head> Defines the header of the html document
<title> </title> Defines the title of the html document
<body> </body> Defines the body of the html document
<hx> </hx> Defines a level x title, where x has values from 1 to 6
<b> </b> Defines bold text
<i> </i> Defines italic text
<center> </center> Centers the text
<br /> Line break
<p> </p> Paragraph
<ul> </ul> Unordered list
<ol> </ol> Ordered list
<li> </li> List item
<img src=“URL” alt=“text” /> Displays an image from a defined source URL. If not found, than it displays an alternate text.
<a href=“URL”> </a> Anchor to a defined URL
<hr /> Horizontal line

© 2013 SAP AG. All rights reserved. Internal 14


2. HTML – Example
Example:
<html>
<head>
<title>Test Page</title>
</head>
<body>
<h1>Test Page</h1>
<p>Hello World</p>
<p>Here are some good resources about HTML</p>
<ul>
<li><a href="http://www.w3.org/TR/html401/">HTML 4.01, the most
recent finished specification (1999)</a></li>
<li><a href="http://dev.w3.org/html5/spec/spec.html">HTML5, the
upcoming version of HTML</a></li>
<li><a href="http://www.w3.org/MarkUp/Guide/">Dave Raggett's
Introduction to HTML</a></li>
<li><a href="http://www.cs.tut.fi/~jkorpela/html/empty.html">Empty
elements in SGML, HTML, XML and XHTML</a></li>
<li><a href="http://computemagazine.com/man-who-invented-world-
wide-web-gives-new-definition/">Tim Berners-Lee Gives the Web a New
Definition</a></li>
<li><a href="http://webdeconstructor.com/">HTML analyzer</a></li>
</ul>
<br />
<p>Try <b>not</b> to use W3CSchools as a
reference!</p>
</body>
</html>
© 2013 SAP AG. All rights reserved. Internal 15
2. HTML – Tables
Table tags
 <table> </table> represents a table
 <tr> </tr> represent a table row
 <td> </td> represents table data (a cell value)
 <th> </th> represents a table header value

Example:
<table>
<tr>
<th>Header1</th> <th>Header2</th>
</tr>
<tr>
<td>Cell Value 1</td><td>Cell Value 2</td>
<tr>
</table>

© 2013 SAP AG. All rights reserved. Internal 16


2. HTML – Forms

HTML Forms
 <input type=“text” name=“” size=“” maxlength=“” /> - textbox

 <input type=“radio” name=“” value=“” /> - radio checkbox

 <input type=“checkbox” name=“” checked=“” /> - checkbox

 <input type=“password” name=“” size=“” maxlength=“” /> - password textbox

 <input type=“reset/submit” onclick=“” /> - action button

 <input type=“image” name=“” align=“” src=“” /> - image

 <input type=“hidden” /> - hidden field

 <select name=“” option=“” multiple=“” /> - selection list

 <textarea name=“” cols=“” rows=“” wrap=“” /> text area

© 2013 SAP AG. All rights reserved. Internal 17


2. HTML – HTML5

HTML5

• It’s an extension and not a replacement

• It relies upon JavaScript and CSS support


• Orientated towards multimedia applications and content optimization

Some new features

• The <canvas> tag for 2D drawing

• The <video> and <audio> tags for video and audio playback

• File API for local browser storage

• Content specific elements like <article> <footer> <header> <nav> <section>

• New form controls for timing (calendar, date, time), email, searching, etc.
© 2013 SAP AG. All rights reserved. Internal 18
2. HTML – Document Object Model (DOM)

Document Object Model (DOM)

• Convention for representing and interaction of objects in HTML, XHTML and XML documents.

• When the HTML page is loaded by the browser, it becomes a document object.

• Everything is a node
o The document itself is a document node
o All HTML elements are nodes
o All HTML attributes are attribute nodes
o Text inside HTML elements are text nodes
o Comments are comment nodes

© 2013 SAP AG. All rights reserved. Internal 19


2. HTML – Document Object Model (DOM)

Document Object Model (DOM)

• Tree-like model

• A node with a given ID can exist


only once

© 2013 SAP AG. All rights reserved. Internal 20


2. HTML – Typical HTML Page Header
Typical HTML Page Header
<!DOCTYPE HTML>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>

<meta http-equiv="X-UA-Compatible" content="IE=edge" />

<link rel="shortcut icon" type="image/x-icon" href=“path/to/my/favicon.ico" />

<link rel="stylesheet" type="text/css" href=“path/to/my/css/file.css" />

<title>Title of my web page</title>

<script src=“path/to/my/js/file.js“ type=“text/javascript”></script>

</head>

<body>…</body>

<html>

© 2013 SAP AG. All rights reserved. Internal 21


2. HTML , CSS and JavaScript – Advantages and Disadvantages
Major Advantages
 Speed
 Simplicity
 Versatility
 Server load
 Open-source
 Open-standards
 Very easy to learn

Major Disadvantages
 Very vulnerable to reverse engineering
 Reliance on the end-user
 Security

© 2013 SAP AG. All rights reserved. Internal 22


3. HTTP
Making the Internet possible since 1991
3. HTTP – Overview
Hypertext Transfer Protocol
• Stateless protocol

• Client-server design - communication is represented by request and response messages

• Request message format:


• HTTP_METHOD /path_to_resource HTTP/version_no

• List of <Header-name-1: value>

• [optional] Request body

• Response message format:


• HTTP/version_no status_code

• List of <Header-name-1: value>

• Response body
© 2013 SAP AG. All rights reserved. Internal 24
3. HTTP – HTTP Methods
.

HTTP Method Name Description


GET Requests a web resource
HEAD Requests the header of a web resource
POST Adds to a web resource
PUT Saves a web resource
DELETE Deletes a web resource
TRACE Echoes back the received request
OPTIONS Requests the list of HTTP methods supported by the web server
CONNECT Used for TCP/IP tunnel based connections

© 2013 SAP AG. All rights reserved. Internal 25


3. HTTP – Request Example
Web Page
<html>
<head>
<title>Form Example</title>
</head>
<body>
<h1>Form Example</h1>
<form action="https://www.google.com/finance?q" method="get">
Company: <input size="25" name="q">
<input type="submit" value="Get Quote">
</form>
</body>
</html>

The browser builds the URL: https://www.google.com/finance?q=SAP

The browser sends the HTTP request


GET /finance?q=SAP HTTP/1.1
HOST: www.google.com
….
© 2013 SAP AG. All rights reserved. Internal 26
3. HTTP – Status Codes
.
Status code Meaning Example
format
1xx Information 100 – the web server accepts the client’s request for…
2xx Success 200 – the request was successful
3xx Redirection 301 – the web page was permanently moved to…
4xx Client error 404 – the requested web resource was not found
5xx Server error 500 – Server internal error

© 2013 SAP AG. All rights reserved. Internal 27


3. HTTP – The Web Browser

The Web Browser


 HTML interpreter plus HTTP client plus future application host engine

 Two major components (engines): the rendering (layout) engine and the JavaScript engine

 First browser war (in the 90’s)

– Casus belli: bad Internet end-user experience

– Won by Mozilla because of JavaScript

– Side effects: browser plugins

 Second browser war (in the 2000’s)

– Casus belli: browsers plugins

– Won by HTML5

– Side effects: the HTML5 hype

©The big 5: Microsoft Internet Explorer, Mozilla Firefox, Google Chrome, Opera, Apple Safari
2013 SAP AG. All rights reserved. Internal 28
3. HTTP – The Web Browser

The big 5 browsers (rendering engine + JavaScript engine)


 Microsoft Internet Explorer (Trident + Chakra)

 Mozilla Firefox (Geko + SpiderMonkey)

 Google Chrome (WebKit + V8)

 Opera (Blink (based on WebKit) + Carakan)

 Apple Safari (WebKit + Nitro)

The biggest challenge: make the same web page look the same on all big browsers

Always use the latest versions!

© 2013 SAP AG. All rights reserved. Internal 29


4. JavaScript
How to speak Internet!
4. JavaScript - History

 Created in 1995 by Brendan Eich, ex Netscape, currently CTO of Mozilla Corporation

 Netscape -> Sun -> Oracle

 Prototype-based, multi-paradigm, case-sensitive scripting language

 Ubiquitous, de facto language of the Internet

 Not related to Java (marketing at its finest)

 Formalized as ECMAScript (ECMA-262)


o 1999 – ECMAScript 3
o 2009 – ECMAScript 5

© 2013 SAP AG. All rights reserved. Internal 31


4. JavaScript - Overview

 Object oriented dynamic language

 Syntax similar to C and Java

 No classes, but object prototypes

 Functions are objects and objects are functions

 Automatic garbage collection

 It is not compiled into byte/machine code

 World’s Most Misunderstood Programming Language

© 2013 SAP AG. All rights reserved. Internal 32


4. JavaScript - Runtime

JavaScript Engines

 Browsers, sandbox environment

– Mozilla Firefox (Geko + SpiderMonkey) => F12

– Microsoft Internet Explorer (Trident + Chackra) => F12

– Google Chrome (WebKit + V8) => F12

 Server-side engines

– NodeJS

– Microsoft Windows 8

 Different interpretation of ECMAScript standard

© 2013 SAP AG. All rights reserved. Internal 33


4. JavaScript – Frameworks

 jQuery, jQueryUI

 ExtJS

 Google Web Toolkit (Java compiled to JavaScript)

 Prototype

 Scriptaculo.us

 Qooxdoo (It’s former author is the leading developer of SAP UI5)

 KnockoutJS

 BackboneJS

 SAP UI5

© 2013 SAP AG. All rights reserved. Internal 34


4. JavaScript – Community

 De facto language of the Internet

 Usually open-source

 Runs on the end’s user machine

 Easy to view (if not minified)

 Easy to modify (and override)

 Easy to hack

 Content Delivery Networks:


<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.js"></script>

<script>

(window.jQuery || document.write('<script src="/scripts/jquery-1.9.0.min.js"><\/script>'));

</script>

© 2013 SAP AG. All rights reserved. Internal 35


4. JavaScript – References And Playground

 JavaScript Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference

 JavaScript Guide: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide

 “JavaScript: The Good Parts”, by Douglas Crockford

 DO NOT rely on w3schools tutorials! (no connection with w3c, errors, false statements)

 Playground:

– On premise IDEs, with IntelliSense and AutoComplete


o Eclipse (free), Microsoft Visual Studio ($$$), Microsoft WebMatrix (free), Sublime ($), JetBrains WebStorm ($$), etc

– On premise IDEs without IntelliSense and AutoComplete: Notepad++ (free), etc

– Online IDEs: JsFiddle, Plunker, Cloud9

– Browsers console (F12)

© 2013 SAP AG. All rights reserved. Internal 36


4. JavaScript
The Building Blocks
4. JavaScript – Building Blocks

 Numbers (values) – no differences between integers or doubles; all numbers are numbers

 Strings (values) – separated by “ or ‘

 Variables – they begin with keyword var

 Operators

 Expressions – evaluate to a value

 Statements – usually finished with “;”

 Whitespaces – should be eliminated in the release version (minified)

 Functions

 Objects

© 2013 SAP AG. All rights reserved. Internal 38


4. JavaScript – Numbers
• Numbers are "double-precision 64-bit format IEEE 754 values"

• No distinct types for float or integer

• Standard numeric operators:


+ : Addition
- : Subtraction
* : Multiplication
/ : Division
% : Modulus
++ : Increment
-- : Decrement

• Convert strings to numbers with parseInt or parseFloat

• Math object supplies more advanced methods and constants

© 2013 SAP AG. All rights reserved. Internal 39


4. JavaScript – Converting Strings to Numbers
 Convert to integer using parseInt(n,base)
 parseInt() takes the base for conversion as an optional second parameter
 Examples:
parseInt("123", 10)  123
parseInt("010", 10)  10
parseInt("010")  8 // leading zero implies octal
parseInt("Hello")  NaN
parseInt("FF", 16)  255

 Convert to float with parseFloat(n)

 Alternatively you can use the unary plus operator


+ "23"  23
parseInt("123Hello",10)  123
+ "123Hello"  NaN

© 2013 SAP AG. All rights reserved. Internal 40


4. JavaScript – The Math Object

 Built-in object with properties and methods for mathematical constants and functions

 Constants: E, LN2, LN10, LOG2E, LOG10E, PI, SQRT1_2, SQRT2

 Functions: abs, acos, asin, atan, atan2, ceil, cos, exp, floor, log, max, min,
pow, random, round, sin, sqrt, tan

 Examples:
 Math.PI  3.141592653589793
 Math.random()
 Math.max(1,2,4,8,16)  16

© 2013 SAP AG. All rights reserved. Internal 41


4. JavaScript – NaN

 The special value NaN (Not a number) is returned for invalid mathematical operations
 parseInt("Hello", 10)  NaN
 NaN + 10  NaN

 Test for NaN with isNaN()


 isNaN(parseInt("Hello"))  true

 There are also special values for Infinity and –Infinity


 1 / 0  Infinitity
 -1 / 0  -Infinity

 Test for Infinity with isFinite()


 isFinite(1/0)  false
 isFinite(NaN)  false

© 2013 SAP AG. All rights reserved. Internal 42


4. JavaScript – Strings
 Strings are sequences of Unicode characters

 .length returns the length of a string

 Concatenation with plus operator (or .concat() Method)


 "Hello" + "World"  "HelloWorld"

 Some string methods:


 substr(index, length)
 toUpperCase()
 replace(search, replace)

 Concatenation and addition


 "Hello" + 42  "Hello42"
 1 + 2 + "x" + 3  "3x3"

© 2013 SAP AG. All rights reserved. Internal 43


4. JavaScript – Other Types

 Null
 null is a deliberate non-value

 Undefined
 undefined indicates an uninitialized value

 Date

 Booleans
 true and false
 falsy values are:
 false, 0, the empty string (""), NaN, null, and undefined
 all other values evaluate to true

© 2013 SAP AG. All rights reserved. Internal 44


4. JavaScript - Variables

 Standard way to define variables


var firstName = “Bogdan”;

var lastName = null;


 Alternative way to define variables (jslint prefers this)
var firstName = “Bogdan”, lastName = null;

 Variables declared outside functions are global

 Omitting the var keyword inside a function makes the variable global!

© 2013 SAP AG. All rights reserved. Internal 45


4. JavaScript - Operators

 Binary operators: +, -, *, /, %,

 Unary operators: ++, --

 Logical operators: &&, ||

 Comparison operators: <, <=, >, >= - work with both numbers and strings

– Equality (==) and inequality (!=) perform type coercion


o 1 == 1 => true
o 0 == “0” => true
o 1 != true => false

– === and !== do not perform type coercion


o 1 === true => false
o 1 !== “1” => true

© 2013 SAP AG. All rights reserved. Internal 46


4. JavaScript - Truth

 Boolean values: true, false

 Boolean operations

– && (and)

– || (or)

– != /!== (not)

 Falsy values

– null, undefined, NaN, “”, ‘’ (empty strings), 0

 Truthy values

– Everything else

 == (equal) vs. === (exact equality)

© 2013 SAP AG. All rights reserved. Internal 47


4. JavaScript – Syntax

var x = 10;
Comments (C like)
if ( x == 2 ) {
 Single line comments // do something
// this is a comment } else {
// do something else
 Block comments }

/*
while ( x < 11 ) {
This is a block comment, // loop forever
}
spanning multiple lines
*/
for ( var i = 0; i < x; i++ ) {
console.log(i);
}
Control structures (C like)
 if / else switch ( x ) {
case 10:
console.log( "x is 10" );
 while / do-while break;
default:
 for / for in console.log( "x is not 10" );
}
 switch statement

© 2013 SAP AG. All rights reserved. Internal 48


4. JavaScript - Braces

 Braces DO NOT create scope!

 Due to a design blunder in JavaScript return statement, ALWAYS use the K&R style for open braces

– K&R style (CORRECT):


return {
status: “ok”
};

– Allman style (BAD):


return
{
status: “ok”
};

© 2013 SAP AG. All rights reserved. Internal 49


4. JavaScript – Reserved Keywords

 These may not be used as variables, functions, methods or object identifiers

abstract, as, boolean, break, byte, case, catch, char, class, continue, const,
debugger, default, delete, do, double, else, enum, export, extends, false, final,
finally, float, for, function, goto, if, implements, import, in, instanceof, int,
interface, is, long, namespace, native, new, null, package, private, protected,
public, return, short, static, super, switch, synchronized, this, throw, throws,
transient, true, try, typeof, use, var, void, volatile, while, with

 Not all of these words are actually used in JavaScript

© 2013 SAP AG. All rights reserved. Internal 50


4. JavaScript
Objects
4. JavaScript – Objects { }

 Objects are collections of name-value (Maps) pairs, like HashMaps in Java or


HashTables in C

 Everything (except core types) is an object in JavaScript!

 The name part is a JavaScript string

 The value part can be an JavaScript value – including more objects => complex
object structures

© 2013 SAP AG. All rights reserved. Internal 52


4. JavaScript – Creating Objects

 The preferred way, using object literal syntax:


 var obj = {};
 var vegetable = {
name: "Pumpkin",
details: {
color: "orange",
size: 12
}
};

 Alternative syntax:
 var obj = new Object();

© 2013 SAP AG. All rights reserved. Internal 53


4. JavaScript – Setters And Getters

 Set and get object properties via keys or dot syntax


 obj["name"] = "Doe“ //setter
 obj.name = "Doe“ //setter
 obj["name"] //getter  "Doe"
 obj.name //getter  "Doe"

 Chaining properties
 vegetable.details.color  "orange"
 vegetable["details"]["size"]  12

 var key = "details";


vegetable[key].color;  "orange„
 Properties can be „added on the fly“
© 2013 SAP AG. All rights reserved. Internal 54
4. JavaScript – Arrays [ ]

 Arrays are a special type of object

 Initialize an array using the array literal


 var animalsAndMore = ["dog", "cat", "cow“, 1, false, null];

 The length of an array is one more than the highest index


 animals.length  3
 animals[99] = "donkey"
animals.length  100

 Accessing non-existent indexes returns undefined

 The only collection type in JavaScript

© 2013 SAP AG. All rights reserved. Internal 55


4. JavaScript – Iterating Over Arrays

 Iterate over array with for


 for (var i = 0, len = animals.length; i < len; i++) {
// Do something with animals[i]
}

 or for…in
 for (var i in animals) {
// Do something with animals[i]
}
 but beware that this will also include new properties that may have been added to array.prototype

© 2013 SAP AG. All rights reserved. Internal 56


4. JavaScript – Array Methods

 Append items with a[a.length] = item or a.push(item, …)

 Other array methods

concat returns a new array with the items added on to it.


join joins array elements into a string, separated by the separator
pop removes and returns the last item
push adds one or more items to the end (like our ar[ar.length] idiom)
slice returns a sub-array
sort takes an optional comparison function
splice lets you modify an array by deleting a section and replacing it with more items

unshift prepends items to the start of the array

© 2013 SAP AG. All rights reserved. Internal 57


4. JavaScript – Determining Type

var myFunction = function() { console.log("hello"); };


var myObject = { foo : "bar" };
var myArray = [ "a", "b", "c" ];
var myString = "hello";
var myNumber = 3;

typeof myFunction; // returns 'function'


typeof myObject; // returns 'object'
typeof myArray; // returns 'object'!!!
typeof myString; // returns 'string';
typeof myNumber; // returns 'number'
typeof null; // returns 'object'!!!

// jQuery to the rescue


jQuery.isArray(myArray); // returns true

© 2013 SAP AG. All rights reserved. Internal 58


4. JavaScript – The Date Object
 The Date objects supply methods to work with dates and time

 The Date object can only be instantiated with the Date() constructor
new Date()
new Date(milliseconds) // since Jan 1st, 1970
new Date(dateString)
new Date(year, month, day [, hour, minute, second, millisecond ])

 var today = new Date();


var myBirthday = new Date("1972 Jan 03");

 Methods
getDate(), getDay(), getFullYear(), getMonth() (zero-based), getTime(),
toDateString(), toLocaleDateString()

© 2013 SAP AG. All rights reserved. Internal 59


4. JavaScript – Regular Expressions

 Regular Expressions are defined with the RegExp()-constructor


or between slashes (/)
var re = new RegExp("\\w+");
var re = new RegExp(pattern, modifiers);
var re = /\w+/;
var re = /pattern/modifiers

 Matching a hex-color:
var regex = /^#?([a-f0-9]{6}|[a-f0-9]{3})$/i
var color = "#ABC";
var color2 = "red";
regex.exec(color);  [ "#ABC", "ABC" ]
regex.test(color);  true
color2.match(regex);  null

 more on Regular Expressions:


 https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp

© 2013 SAP AG. All rights reserved. Internal 60


4. JavaScript – JavaScript Object Notation (JSON)

 JSON is a ligthweight data exchange format. var address = {


"firstName": "John",
"lastName" : "Smith",
"age" : 25,
 JSON strings look like JavaScript Objects "address" :
{
 but they cannot contain functions "streetAddress": "21 2nd Street",
 the keys have to be quoted "city" : "New York",
"state" : "NY",
"postalCode" : "10021"
},
 JSON doesn't need to be parsed, becomes JavaScript "phoneNumber":
Object immediately [
{
"type" : "home",
"number": "212 555-1234"
 All modern browser have built-in JSON support },
{
"type" : "fax",
 Online Validator: http://jsonlint.com/ "number": "646 555-4567"
}
]
}

© 2013 SAP AG. All rights reserved. Internal 61


4. JavaScript
Functions
4. JavaScript – Functions
• A basic, global function
function add(a, b) {
var total = a + b;
return total;
}

 Functions can take zero or more named parameters

 Hoisting: in the background all the function are “hoisted” to the top of the file, so one can use a function before
defining it.

 Variables declared inside the function body are local. If the var keyword is omitted, the variable will
be registered globally once the function runs.

 The return statement returns a value and can be used at any time. It terminates the execution of
the function. Functions without a return statement return undefined

© 2013 SAP AG. All rights reserved. Internal 63


4. JavaScript – Scope

 Braces DO NOT create scope, functions create scope!

 Global scope vs. Local scope:


var constant = 32; // global variable
function celsiusToFarenheit (temp) {
var farenheitTemp = temp * 9/5 + constant; // local variable
return farenheitTemp;
}
if(constant < 40) {
var doubleConstant = constant * 2; //global variable
}

© 2013 SAP AG. All rights reserved. Internal 64


4. JavaScript – Calling Functions
 Calling a function without the expected parameters will set them to undefined
 add();  NaN // x and y are undefined

 It is also possible to supply more parameters than expected


 add(1, 2, 3);  3 // the third parameter is ignored

 Functions can access all parameters through arguments


 arguments is an array-like object holding all passed values
 function avg() {
var sum = 0;
for (var i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
return sum / arguments.length;
}
avg(1,4,10);  5

© 2013 SAP AG. All rights reserved. Internal 65


4. JavaScript – Parameters And Defaults
 JavaScript function parameters can't have default values in function declaration

 Using an object to pass parameters to a function makes the parameters easily extendable

 var foo = function(oOptions) {


if (!oOptions) { // catch undefined oOptions param
oOptions = {};
}
oOptions.param1 = oOptions.param1 || "hello";
oOptions.param2 = oOptions.param2 || "world";
return oOptions.param1 + " " + oOptions.param2;
}

© 2013 SAP AG. All rights reserved. Internal 66


4. JavaScript – Anonymous Functions

 var avg = function() {


var sum = 0;
for (var i = 0, j = arguments.length; i < j; i++) {
sum += arguments[i];
}
return sum / arguments.length;
}

 Equivalent to function avg()

© 2013 SAP AG. All rights reserved. Internal 67


4. JavaScript – Self-Executing Anonymous Functions

 Pattern: (function() { /* code */ } () );

 Wrapper around code, to protect it from global namespace

 Hides the implementation from external code

 Runs once ad only once

 jQuery is implemented as a self-executing anonymoyus function

 Example:

(function() {
var parts = ["Tires", "Engine", "Axles"];
function assemble() { console.log( "Assembling " + parts.join(', ')); }
assemble();
}());
© 2013 SAP AG. All rights reserved. Internal 68
4. JavaScript
Closure
4. JavaScript – Closure 1

“Closure means that inner function always has access to the vars and parameters of its outer function,
even after the outer function has returned” – Douglas Crockford
function myNonCosure() {
var date = new Date(); //variable lost after function returns
return date.getMilliseconds();
}

function myClosure() {
var date = new Date(); //variable stays around even after return
return function() {
return date.getMilliseconds();
};
}

© 2013 SAP AG. All rights reserved. Internal 70


4. JavaScript – Closure 2

window.onload = function() {

var output = document.getElementById(‘output’);

output.innerHTML = myNonClosure();

window.setTimeout(function () {

output.innerHTML += ‘<br />’ + myNonClosure();

}, 500);

//returns 2 different values!

© 2013 SAP AG. All rights reserved. Internal 71


4. JavaScript – Closure 3

window.onload = function() {

var output = document.getElementById(‘output’);

var closure = myClosure();

output.innerHTML = closure ();

window.setTimeout(function () {

output.innerHTML += ‘<br />’ + closure ();

}, 500);

//returns same value!


© 2013 SAP AG. All rights reserved. Internal 72
4. JavaScript – Closure 4

Closure means returning the scope from the time the function was created and not the time when the
function was run.

var scope = “global”;


function testScope() {
var scope = “local”;
function innerFunc() { return scope; }
return innerFunc;
}
var innerFunc = testScope();
var result = innerFunc(); //returns “local”

© 2013 SAP AG. All rights reserved. Internal 73


4. JavaScript – Recursion

 Recursive functions are smaller and more elegant, and occupy less stack space (if this was ever a problem)
 Any recursive function can be written iteratively
 Examples:
function func1(num, exp) {
if (exp === 0) { return 1; }
return num * func1(num, exp-1);
}

function nonRecursiveFunc(num, exp) {


var retVal = 1;
for ( var i = 0; i < exp; i++ ) {
retVal *= num;
}
return retVal;
}
© 2013 SAP AG. All rights reserved. Internal 74
4. JavaScript – Method Chaining (Cascading)

 If a function returns this instead of undefined it cascades

 Cascading is a common pattern in jQuery and SAPUI5

 Nice time-saver (the element in the example has to be looked up only once)

 Debugging long method chains is more difficult

 Example:
jQuery("#myButton").text("Click me").css("color", "#c00");

© 2013 SAP AG. All rights reserved. Internal 75


4. JavaScript
Structuring Code Using Patterns
4. JavaScript – Structuring Code Using Patterns

 The Prototype Pattern


 The Module Pattern
 The Revealing Module Pattern
 The Revealing Prototype Pattern

© 2013 SAP AG. All rights reserved. Internal 77


4. JavaScript – The Prototype Pattern 1

Pros
 Leverage JavaScript built-in features

 Modularize code into re-usable objects

 Variables/functions taken out of global namespace

 Functions loaded into memory only once

 Possible to override functions through prototyping

 Uppercase convention, looks like classic OOP

Cons
 “this” keyword can be tricky

 Constructor is separated from prototype definition

© 2013 SAP AG. All rights reserved. Internal 78


4. JavaScript – The Prototype Pattern 2

var Calculator = function (eq) {


this.eqCtl = document.getElementById(eq);
};

Calculator.prototype = {
add: function (x, y) {
var val = x + y;
this.eqCtl.innerHTML = val;
}
}
var calc = new Calculator(‘myDiv’);
calc.add(2,2);

© 2013 SAP AG. All rights reserved. Internal 79


4. JavaScript – The Prototype Pattern 3

• Extension – override functionality without modifying the original source code.

• Example:

Calculator.prototype.add = function (x, y) {

var val = x – y;

this.eqCtl.innerHTML = val;

};

© 2013 SAP AG. All rights reserved. Internal 80


4. JavaScript – The Prototype Pattern 4 – Extensions Example
IE8 implements ECMAScript v3, so there is no “filter” method for Array objects. Don’t ask why…
<script>
if (!Array.prototype.filter) {
Array.prototype.filter = function(fun /*, thisp*/) {
if (this == null) throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun != "function") throw new TypeError();
var res = [];
var thisp = arguments[1];
for (var i = 0; i < len; i++) {
if (i in t) {
var val = t[i];
if (fun.call(thisp, val, i, t))
res.push(val);
} }
return res;
} }
</script>

© 2013 SAP AG. All rights reserved. Internal 81


4. JavaScript – The Prototype Pattern 5 - Namespaces

var myNameSpace = myNameSpace || { };


myNameSpace.Calculator = function (tb, eq) {
this.eqCtl = document.getElementById(eq);
};
myNameSpace.Calculator.prototype = {
add: function (x, y) {
var val = x + y;
this.eqCtl.innerHTML = val;
}
}
var calc = new myNameSpace.Calculator(‘myDiv’);
calc.add(2,2);

© 2013 SAP AG. All rights reserved. Internal 82


4. JavaScript – The Module Pattern 1

Pros
 Modularize code into re-usable objects

 Variables/functions taken out of global namespace

 Exposes only public members while hiding private ones

 Uppercase convention, feels like classic OOP

Cons
 Functions may be duplicated across objects in memory when not using singleton

 Not easy to extend

 Debugging….

© 2013 SAP AG. All rights reserved. Internal 83


4. JavaScript – The Module Pattern 2

var Calculator = function (eq) {


var eqCtl = document.getElementById(eq); //private member
return {
add: function (x, y) { //public member
var val = x + y;
eqCtl.innerHTML = val;
}
};
};
var calc = new Calculator(‘myDiv’);
calc.add(2,2);

© 2013 SAP AG. All rights reserved. Internal 84


4. JavaScript – The Revealing Module Pattern 1

Pros
 Modularize code into re-usable objects

 Variables/functions taken out of global namespace

 Exposes only public members

 Cleaner way to expose public members

Cons
 Functions may be duplicated across objects in memory when not
using singleton

 Not easy to extend

 Debugging….

© 2013 SAP AG. All rights reserved. Internal 85


4. JavaScript – The Revealing Module Pattern 2

var calculator = function (eq) {


var eqCtl = document.getElementById(eq),
doAdd = function (x, y) {
var val = x + y;
eqCtl.innerHTML = val;
};
return { add: doAdd }; //expose public member
}(‘myDiv’);

calculator.add(2,2);

© 2013 SAP AG. All rights reserved. Internal 86


4. JavaScript – The Revealing Prototype Pattern 1

Pros
 Combines Prototype and Revealing Module patterns

 Modularize code into re-usable objects

 Variables/functions taken out of global namespace

 Expose only public members

 Functions loaded into memory once

 Extensible

Cons
 “this” keyword can be tricky

 Constructor is separated from prototype definition

© 2013 SAP AG. All rights reserved. Internal 87


4. JavaScript – The Revealing Prototype Pattern 2

var Calculator = function (eq) {


this.eqCtl = document.getElementById(eq);
};

Calculator.prototype = function() {
var add = function (x, y) {
var val = x + y;
this.eqCtl.innerHTML = val;
};
return { add : add };
}();
var calc = new Calculator(‘myDiv’);
calc.add(2,2);
© 2013 SAP AG. All rights reserved. Internal 88
4. JavaScript
this in Different Contexts
4. JavaScript – this in Different Contexts

function myFunc() { • Beware: functions can be


this.attr = "yo"; invoked as functions and to
} create objects

/* if invoked like a function, • If the function is invoked via a


"this" is the global object */ function call, the this object is
myFunc(); the global object
alert(attr); // "yo"
• If the function is invoked via the
/* if invoked to create a new new statement, this is the new
object, "this" is the new object
object */
var myObject = new myFunc(); • So, this is not defined by the
alert(myObject.attr); // "yo" function but the way the function
is invoked!

© 2013 SAP AG. All rights reserved. Internal 90


4. JavaScript – this in Different Contexts

var test = { • Calling a function with the


prop1: "", method invocation pattern
myMethod: function(sParam) { obj.method() sets this within
this.prop1 = sParam; the function to the object obj
}
}

/* when invoking a function with


the method invocation pattern
"obj.method()", then "this"
within the function becomes the
object "obj" */

test.myMethod("hello");

© 2013 SAP AG. All rights reserved. Internal 91


4. JavaScript – this in Different Contexts

function myFunc(sLast, sFirst) { • Call and apply are built-in JavaScript functions
this.attr = sFirst + " " + sLast;
} which let one specify which object „this“ should
refer to when a specific function is called
var myObj = {};

// apply calls the function and passes myObj • With this one can „borrow“ functions/ methods of
// as "this" and the argument array
myFunc.apply(myObj, ["Doe", "John"]);
other objects for one‘s own objects
alert(myObj.attr); // "John Doe"
• Call and apply are really the same functions, the
var myObj2 = {};
only difference is that apply needs to get the
// call calls the function and passes myObj parameters for the function call in an array,
// as "this" and the arguments
myFunc.call(myObj2, "Doe", "John"); whereas call needs them listed one after another
alert(myObj2.attr); // "John Doe"

© 2013 SAP AG. All rights reserved. Internal 92


4. JavaScript – this in Different Contexts

. function myFunc() { • When one sets the "this" parameter to an


return this;
} undefined value, the runtime replaces it with
the global object! This allows to handle both
// using undefined as scope
myFunc.call(); // global object cases, function and method calls, with the
myFunc.apply(); // global object same code.
// using an object as scope • Second important thing: when using a literal
myFunc.call({}); // object: {} (string, number, boolean) as the value for the
myFunc.apply({}); // object: {}
“this” parameter, the runtime automatically
// using primitives as scope converts it to the corresponding wrapper
// (converts them to object)
f.call("abc", ...) object, because this must be an object!
// f.call(new String("abc"), ...) • The strict equality check will not work since
// this will not work! this is the String object and not the primitive.
jQuery.each(["a", "b", "c"], function() {
if (this === "a") { alert(this) };
});

© 2013 SAP AG. All rights reserved. Internal 93


4. JavaScript
The Prototype Object
4. JavaScript – The Prototype Object 1

• 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 they are 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 themselves objects, every
prototype has a prototype too (There is only one exception, the default object prototype at the
top of every prototype chain).
• With prototype chains you can define an inheritance chain for JavaScript objects.

• Further reading: Understanding JavaScript Prototypes

© 2013 SAP AG. All rights reserved. Internal 95


4. JavaScript – The Prototype Object 2

function Employee() {}; • Each function has a prototype object


var myEmployee1 = new Employee();
• If one defines properties or methods for this
Employee.prototype.myAttr = "test"; prototype object, all objects created via the
Employee.prototype.myFunction = function() { function will get these properties and
alert("yo!"); methods, even if the creation of the object
} was before the property or method
definition.
var myEmployee2 = new Employee();
• An advantage of using prototype as
alert(myEmployee1.myAttr); // "test" opposed to defining methods in the
alert(myEmployee2.myAttr); // "test" constructor functions is that using prototype
all objects use the same function as
myEmployee1.myFunction(); // "yo!" opposed to copied one
myEmployee2.myFunction(); // "yo!"

© 2013 SAP AG. All rights reserved. Internal 96


4. JavaScript – The Prototype Object 3

// creation via functions


. var myEmployee = new Employee();
• One can think of the red, commented code as something
that the JS runtime does implicitly
// constructor function execution
function Employee() {

// create a new object via literal


• When a function is invoked via "new", a new object called
var this = { "this“ is being created. This new object has a hidden link to
__proto__ = Employee.prototype
}; the function‘s prototype object.
// add properties and methods to the
// object • This new object inherits methods and properties from the
this.property = "propValue";
this.method = function () {}; prototype object. If a method or a property is not found on
// implicitly return this instance
the new object the prototype will be checked.
return this;

} • The prototype object always has the reference to the origin


Employee.prototype = {
constructor function.
constructor: Employee
};

© 2013 SAP AG. All rights reserved. Internal 97


4. JavaScript
Events
4. JavaScript - DOM API - Event Handling

. // <input type=button id="button" value="go"> • Unfortunately, the implementation of JavaScript and its
var oButton = related DOM methods differed from browser to browser in
document.getElementById("button"); the past. Especially the IE until version 8 was different

• The main difference was the event model


if (oButton.addEventListener) {
// this is for DOM compliant browsers
oButton.addEventListener("click", myHandler); • With IE9 the situation has become much better, all
} else if (oButton.attachEvent) { browser are almost equal.
// this is IE6 to IE8
oButton.attachEvent("onclick", myHandler);
} • The example shows how one should use „feature
detection“ and not check for particular browser versions

function myHandler() {
alert("click");
}

© 2013 SAP AG. All rights reserved. Internal 99


4. JavaScript - DOM API - Event Handling via Feature Detection

. // the document.all property only exists in IE • Rather than checking for a certain browser,
var bIsIE = (document.all) ? true : false;
check for the existence of a feature
// don't
if (bIsIE) {
oButton.attachEvent("onclick", myHandler); • This way, if there is a new browser of the
} else { same family which gains a feature, you don‘t
oButton.addEventListener("click", myHandler);
}
need to change your code. If you check for
the browser you have to regularly update
// better: feature detection your code.
if (oButton.addEventListener) {
oButton.addEventListener("click", myHandler);
} else {
oButton.attachEvent("onclick", myHandler);
}

© 2013 SAP AG. All rights reserved. Internal 100


4. JavaScript - DOM API – Closure for Event Handling

. var myObj = {
prop1: 1,
• In DOM event handlers, „this“ is neither the global
init: function() { object nor the current object, but refers to the DOM
// "this" refers to the object source object of the event.
this.prop1 += 1;

/* store the object reference in a new variable • Storing this in own variables like „that“ or „self“ for
which is available in the closure */
var that = this; usage in closures is a common way to save the
var clickHandler = function(event) {
/* this time, our handler is not a separate
reference to the original object in event handlers
method of the object but a closure
function, having access to the original
object via "that" */ • Closure is a “live” thing. If some other code modifies a
alert(that.prop1); // 2
}
value in the same closure, the changed value will be
visible to your function even if your function has been
document.
getElementById("button"). created a long time before.
addEventListener("click",clickHandler);
}
}
myObj.init();

© 2013 SAP AG. All rights reserved. Internal 101


4. JavaScript
Gotchas
4. JavaScript – Gotchas – Functions And Operators 1

 == vs. ===
o “1” == 1; //true
o Number(“1”) === 1; //true
o “” == 0 //true, the empty string is coerced to Number 0
o 0 == “0” //true, the Number 0 is coerced to String “0”
o “” == “0” //false, both operands are Strings so no coercion is done
o All of last 3 yield false if === is used
 parseInt doesn't assume base 10
o By default, assume a radix 10 => parseInt(“8”) // 8
o If the number begins with 0x, then assume radix 16 => parseInt(“0x8”) // 8
o If the number begins with 0, then some engines assume radix 8 => parseInt(“08”) // 0
 String.replace
o It only replaces the first match, and not all matches
o In order to replace all matches, one must use RegExp

© 2013 SAP AG. All rights reserved. Internal 103


4. JavaScript – Gotchas – Functions And Operators 2

 ‘+’ operator both adds and concatenates


o1 + document.getElementById("inputElem").value; // Concatenates
o1 + Number(document.getElementById("inputElem").value); // Adds
o "3" - "1"; // 2
o3 + ""; // "3“ => ugly convert to string
 typeof – returns the type of an instance of a fundamental type
o typeof {} === "object" //true
o typeof "" === "string" //true
o typeof [] === "array"; //false
o typeof null //object => god knows why…
 instanceof – returns whether the object was constructed using the specified constructor
o "hello" instanceof String; //false
o new String("hello") instanceof String; //true
o ["item1", "item2"] instanceof Array; //true
o new Array("item1", "item2") instanceof Array; //true

© 2013 SAP AG. All rights reserved. Internal 104


4. JavaScript – Gotchas – Constructors 1

JavaScript has the types Object, Array, Boolean, Number, String, and Function.
Each has its own literal syntax and so the explicit constructor is never required.
Explicit (bad) Literal (good)

var a = new Object(); var a = { greet: "hello" };


a.greet = "hello";
var b = new Boolean(true); var b = true;

var c = new Array("one", "two"); var c = ["one", "two"];

var d = new String("hello"); var d = "hello"

var e = new Function("greeting", "alert(greeting);"); var e = function(greeting) { alert(greeting); };

However, if you use the new keyword to construct one of these types, what you actually get is an
object of type Object that inherits the prototype of the type you want to construct (the exception
is Function). So although you can construct a Number using the new keyword, it'll be of type Object:
typeof new Number(123); // "object"
typeof Number(123); // "number"
typeof 123; // "number"

© 2013 SAP AG. All rights reserved. Internal 105


4. JavaScript – Gotchas – Constructors 2

If you write your own constructor function DO NOT forget to include the new keyword:
var Car = function(colour) {
this.colour = colour;
};

var aCar = new Car("blue");


console.log(aCar.colour); // "blue"

var bCar = Car(“red");

console.log(bCar.colour); // error
console.log(aCar.colour); //"blue"

© 2013 SAP AG. All rights reserved. Internal 106


4. JavaScript – Gotchas – Numbers

There is no integer!
 0.1 + 0.2 === 0.3 // false

 0.0 === 0; // true

 var a = 0 * 1; // returns 0

 var b = 0 * -1; // returns -0

 a === b; // true: 0 equals -0

 1/a === 1/b; // false: Infinity does not equal –Infinity

 typeof NaN === "number" // true

 NaN === NaN; // false

© 2013 SAP AG. All rights reserved. Internal 107


4. JavaScript
jQuery
4. JavaScript – jQuery

• Most popular JavaScript framework

• Provides a robust way of manipulating DOM elements

• Cross-browser features

• SAP UI5 is based on jQuery

© 2013 SAP AG. All rights reserved. Internal 109


4. JavaScript – jQuery ready()

• Detect when a page has loaded


o $(document).ready()

• Called once DOM hierarchy is loaded, but before any images are loaded

• Example:
<script type=“text/javascript”>
$(document).ready(function() {
//handle document ready event
});

</script>

© 2013 SAP AG. All rights reserved. Internal 110


4. JavaScript – jQuery Selectors

• Selectors allow page elements to be selected

• Syntax: $(selectorExpression) or jQuery(selectorExpression)

• Selectors by Tag Name

• Selectors by ID

• Selectors by Class Name

• Selectors by Attribute Values

© 2013 SAP AG. All rights reserved. Internal 111


4. JavaScript – jQuery Selectors Example

• By Tag Name:
• $(‘p’) => selects all <p> elements

• $(‘p, a’) => selects all <p> and <a> elements

• $(‘table tr’) => selects all tr elements that are descendants of the
table element

• By ID:
• $(‘#myID’) => selects <any_tag id=“myID”> element

• By Class Name:
• $(‘.myClass’) => selects <any_tag class=“myClass”> element

© 2013 SAP AG. All rights reserved. Internal 112


Thank you
Contact information:

Bogdan MIHAI
Research Scientist, Performance and Insight Optimization
bogdan-eugen.mihai@sap.com
+40 745 394 340

Vous aimerez peut-être aussi