Académique Documents
Professionnel Documents
Culture Documents
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
• Developed between March 1989 and December 1990 by Tim Berners-Lee of CERN
• It is using a client-server architecture: the pages are hosted on servers and visited by clients
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
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
1. A system of globally unique identifiers for web documents – URL (Uniform Resource Locator)
Pattern: scheme://host[:port#]/path/…/[;url-params][?query-string][#anchor]
scheme – the protocol (http, ftp, file, news, mailto, telnet, etc.)
Example: http://www54.sap.com/search/search-results.html?Query=ui5
– Tags, usually they come in pairs (start tag, and end tag)
– Attributes
– Attribute values
Example:
<table>
<tr>
<th>Header1</th> <th>Header2</th>
</tr>
<tr>
<td>Cell Value 1</td><td>Cell Value 2</td>
<tr>
</table>
HTML Forms
<input type=“text” name=“” size=“” maxlength=“” /> - textbox
HTML5
• The <video> and <audio> tags for video and audio playback
• 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)
• 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
• Tree-like model
<html>
<head>
</head>
<body>…</body>
<html>
Major Disadvantages
Very vulnerable to reverse engineering
Reliance on the end-user
Security
• Response body
© 2013 SAP AG. All rights reserved. Internal 24
3. HTTP – HTTP Methods
.
Two major components (engines): the rendering (layout) engine and the JavaScript engine
– Won by HTML5
©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 biggest challenge: make the same web page look the same on all big browsers
JavaScript Engines
Server-side engines
– NodeJS
– Microsoft Windows 8
jQuery, jQueryUI
ExtJS
Prototype
Scriptaculo.us
KnockoutJS
BackboneJS
SAP UI5
Usually open-source
Easy to hack
<script>
</script>
DO NOT rely on w3schools tutorials! (no connection with w3c, errors, false statements)
Playground:
Numbers (values) – no differences between integers or doubles; all numbers are numbers
Operators
Functions
Objects
Built-in object with properties and methods for mathematical constants and functions
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
The special value NaN (Not a number) is returned for invalid mathematical operations
parseInt("Hello", 10) NaN
NaN + 10 NaN
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
Omitting the var keyword inside a function makes the variable global!
Binary operators: +, -, *, /, %,
Comparison operators: <, <=, >, >= - work with both numbers and strings
Boolean operations
– && (and)
– || (or)
– != /!== (not)
Falsy values
Truthy values
– Everything else
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
Due to a design blunder in JavaScript return statement, ALWAYS use the K&R style for open braces
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
The value part can be an JavaScript value – including more objects => complex
object structures
Alternative syntax:
var obj = new Object();
Chaining properties
vegetable.details.color "orange"
vegetable["details"]["size"] 12
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
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 ])
Methods
getDate(), getDay(), getFullYear(), getMonth() (zero-based), getTime(),
toDateString(), toLocaleDateString()
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
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
Using an object to pass parameters to a function makes the parameters easily extendable
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();
};
}
window.onload = function() {
output.innerHTML = myNonClosure();
window.setTimeout(function () {
}, 500);
window.onload = function() {
window.setTimeout(function () {
}, 500);
Closure means returning the scope from the time the function was created and not the time when the
function was run.
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);
}
Nice time-saver (the element in the example has to be looked up only once)
Example:
jQuery("#myButton").text("Click me").css("color", "#c00");
Pros
Leverage JavaScript built-in features
Cons
“this” keyword can be tricky
Calculator.prototype = {
add: function (x, y) {
var val = x + y;
this.eqCtl.innerHTML = val;
}
}
var calc = new Calculator(‘myDiv’);
calc.add(2,2);
• Example:
var val = x – y;
this.eqCtl.innerHTML = val;
};
Pros
Modularize code into re-usable objects
Cons
Functions may be duplicated across objects in memory when not using singleton
Debugging….
Pros
Modularize code into re-usable objects
Cons
Functions may be duplicated across objects in memory when not
using singleton
Debugging….
calculator.add(2,2);
Pros
Combines Prototype and Revealing Module patterns
Extensible
Cons
“this” keyword can be tricky
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
test.myMethod("hello");
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"
. // <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
function myHandler() {
alert("click");
}
. // 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);
}
. 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();
== 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
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)
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"
If you write your own constructor function DO NOT forget to include the new keyword:
var Car = function(colour) {
this.colour = colour;
};
console.log(bCar.colour); // error
console.log(aCar.colour); //"blue"
There is no integer!
0.1 + 0.2 === 0.3 // false
var a = 0 * 1; // returns 0
• Cross-browser features
• 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>
• Selectors by ID
• By Tag Name:
• $(‘p’) => selects all <p> 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
Bogdan MIHAI
Research Scientist, Performance and Insight Optimization
bogdan-eugen.mihai@sap.com
+40 745 394 340