Download as pdf or txt
Download as pdf or txt
You are on page 1of 41

Web applications:

Third part*

Dr. José Luis Zechinelli Martini


joseluis.zechinelli@udlap.mx
LIS – 4052

* This presentation was created using the content of Code School courses and
http://www.w3schools.com
Agenda
ü Data/document models and languages

n Programming Web based applications using JavaScript:


¨ Fundamental concepts
¨ Forest of function expressions
¨ JavaScript best practices

n The client, the Web server, and the storage support

2
Fundamental concepts
n Objects, values, and variables

n Conditionals and loops

n Built-in functions: prompt, alert, confirm, typeof

n JavaScript in an HTML file

n Function declarations

n Using arrays in JavaScript

n Anonymous closures and augmentation

3
Objects and values
n In JavaScript, almost "everything" is an object:
¨ Booleans can be objects (or primitive data treated as objects)
¨ Numbers can be objects (or primitive data treated as objects)
¨ Strings can be objects (or primitive data treated as objects)
¨ Dates are always objects
¨ Maths are always objects
¨ Regular expressions are always objects
¨ Arrays are always objects
¨ Functions are always objects
¨ Objects are objects

n Primitive values are strings ("John Doe"), numbers (3.14), true,


false, null, and undefined

4
String values (1)
n Concatenation operation with:
Ø Spaces: "The meaning of life is " + 42
Ø Expressions: "Platform " + 9 + " and " + 3/4

n Backslash notation with some characters:


Ø Tab stop: "Flight #:\t438\t\tSeat:\t61A"
Ø New line: "Departure:\t09:55A\nArrival:\t14:55P"
Ø Quotation mark: "Login password:\t\t\"C3P0R2D2\""
Ø Backslash itself: "Origin\\Destination:\tOrlando(MCO)\\London(LHR)"

5
String values (2)
n Length property:
Ø "numeral palindrome".length is equal to 18

n Comparisons:
Ø "The Wright Brothers" == "The Wright Brothers" is true
Ø "The Wright Brothers" == "Super Mario Brothers" is false
Ø "The Wright Brothers" != "The Wright brothers" is true

6
Variables
n JavaScript variables can contain single values:
Ø var person = "John Doe";

n Objects are variables too:


¨ They can contain many values
¨ The values are written as name:value pairs (name and value
separated by a colon)
¨ A JavaScript object is an unordered collection of variables called
named values or properties:
Ø var person = { firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue" };

7
Variables names with strings
n Variable names can also access the length property:
var longString = "I would not want to retype this String every time.";
longString.length;

n Finding specific characters within strings:


Ø longString.charAt(0)
Ø longString.charAt(11)
Ø longString.charAt(longString.length – 1)

8
Variables scope
n Local variables:
¨ Variables declared within a function, become LOCAL to the function
¨ Local variables have local scope: They can only be accessed within the
function

n Global variables:
¨ A variable declared outside a function, becomes GLOBAL
¨ A global variable has global scope: All scripts and functions on a web
page can access it

n The lifetime of a variable starts when it is declared:


¨ Local variables are deleted when the function is completed
¨ Global variables are deleted when you close the page

9
Fundamental concepts
ü Objects, values, and variables

n Conditionals and loops

n Built-in functions: prompt, alert, confirm, typeof

n JavaScript in an HTML file

n Function declarations

n Using arrays in JavaScript

n Anonymous closures and augmentation

10
Comparison operators (i=1)
Operator Condition Example
== equal to i == "1"

=== equal value and type i === "1"

!= not equal i != 1

!== not equal value or type i !== "1"

< less than i < 1

<= less than or equal to i <= 1

> greater than i > 1

>= greater than or equal to i >= 1

11
Logical operators
Operator Operation Examples

&& AND (i == 1 && j > 6)

|| OR (i < 1 || j > 10)

! NOT !(i < 3)

12
Conditional instructions
n Ternary operator syntax:
variablename = (condition) ? value1:value2;

n if-else instruction example:


age = Number(age);
if (isNaN(age)) {
voteable = "Error in input";
} else {
voteable = (age < 18) ? "Too young" : "Old enough";
}

13
Loop While: Syntax
while( boolean_expression ) {
code_block;
}

do {
code_block;
} while( boolean_expression );

14
Loop For: Syntax
for( initialize[,initialize];
boolean_expression; update[,update] )
{
code_block;
}

for( variable in object ) {


code_block;
}

15
For/In Loop: Example
var person = { firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue" };

var text = "";


var x;
for( x in person ) {
text += person[x] + ",";
}

16
Fundamental concepts
ü Objects, values, and variables

ü Conditionals and loops

n Built-in functions: prompt, alert, confirm, typeof

n JavaScript in an HTML file

n Function declarations

n Using arrays in JavaScript

n Anonymous closures and augmentation

17
Get and send information
n prompt() sends a message and retrieves an entry from the user:
prompt("What is your name?")

n alert() sends a message to the user in a small pop-up window:


alert("Alert! Alert! Last call to board Train #4!")

n confirm() asks user for consent to move forward with an action:


confirm("Are you sure your name is " + username + "?")

Ø The typeof operator is useful for identifying the type of value inside
a variable or expression

18
Build-in functions: Example
var gotName = false;

while(gotName == false) {
var userName = prompt("What is your name?");

if( confirm("Are you sure your name is " +


username + "?") )
{
alert("Your name was confirmed!");
gotName = true;
}
}

19
Fundamental concepts
ü Objects, values, and variables

ü Conditionals and loops

ü Built-in functions: prompt, alert, confirm, typeof

n JavaScript in an HTML file

n Function declarations

n Using arrays in JavaScript

n Anonymous closures and augmentation

20
JavaScript in an HTML file (1)
n JavaScript can be placed in the <body> and the <head> sections of
an HTML page:
¨ JavaScript code must be inserted between <script> and </script> tags
¨ Or embedding it signaling which JavaScript file to use:
<!DOCTYPE html>
<html>
<head>
<script src="trains.js"></script>
</head>
<body>
<h1>JAVASCRIPT EXPRESS!</h1>

</body>
</html>

21
JavaScript in an HTML file (2)
n JavaScript does NOT have any built-in print or display functions:
¨ Writing into an alert box, using window.alert()
¨ Writing into the HTML output using document.write()
¨ Writing into an HTML element, using innerHTML
¨ Writing into the browser console, using console.log()

n Printing using console.log() method:


Ø trains.js
console.log("Train #" + 1 + " is running.");
console.log("Train #" + 2 + " is running.");
console.log("Train #" + 3 + " is running.");
console.log("Train #" + 4 + " is running.");

22
Ø Supervised work
Fundamental concepts
ü Objects, values, and variables

ü Conditionals and loops

ü Built-in functions: prompt, alert, confirm, typeof

ü JavaScript in an HTML file

n Function declarations

n Using arrays in JavaScript

n Anonymous closures and augmentation

25
JS functions (1)
n Function declaration syntax:
function functionName(parameters) {
code to be executed
}

n Anonymous function example:


var x = function(a, b) {return a * b};
var z = x(4, 3);

n Function() constructor example:


var f = new Function("a", "b", "return a * b");
var z = f(4, 3);

26
JS functions (2)
n Functions are objects:
¨ The typeof operator in JavaScript returns "function" for functions
¨ JavaScript functions have both properties and methods
¨ The arguments.length property returns the number of arguments
received when the function was invoked:
function myFunction() {
return arguments.length;
}

¨ The toString() method returns the function as a string:


var text = myFunction.toString();

27
JS function example
n Function that counts "E's" in a user-entered phrase:
function countE() {
var phrase = prompt("Which phrase would you like to examine?");
if(typeof(phrase) != "string") {
alert("That's not a valid entry!");
return false;
} else {
var eCount = 0;
for(var i = 0; i < phrase.length; i++) {
if(phrase.charAt(i) == 'e' || phrase.charAt(i) == 'E') {
eCount++;
}
}
alert("There are " + eCount + " E's in \"" + phrase + "\".");
return true;
}
}
28
Fundamental concepts
ü Objects, values, and variables

ü Conditionals and loops

ü Built-in functions: prompt, alert, confirm, typeof

ü JavaScript in an HTML file

ü Function declarations

n Using arrays in JavaScript

n Anonymous closures and augmentation

29
JS arrays (1)
n Arrays are a special type of objects:
Ø typeof returns "object" for arrays
Ø They use numbers to access its "elements"

n Creating an array:
Ø var array-name = [item1, item2, ...];
Ø var array-name = new Array( item1, item2, ... );

n An array can have elements of different types:


myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myCars;

30
JS arrays (2)
n The length property of an array returns the length of an array (the
number of array elements)

n The real strength of JavaScript arrays are the built-in array


properties and methods:
¨ valueOf(), join()
¨ pop(), push()
¨ shift(), unshift()
¨ delete()
¨ splice()
¨ sort()
¨ reverse()
¨ concat(), slice()

31
Building a passenger list
n Using an array and functions to keep track of train passengers:
function addPassenger( name, list ) {
if(list.length == 0) {
list.push(name);
} else {
for(var i = 0; i < list.length; i++) {
if(list[i] == undefined) {
list[i] = name;
} else if(i == list.length - 1) {
list.push(name);
}
}
}
return list;
}

32
Removing passengers
n Using an array and functions to keep track of train passengers:
function deletePassenger( name, list ) {
if(list.length == 0) {
console.log("List is empty!");
} else {
for(var i = 0; i < list.length; i++) {
if(list[i] == name) {
list[i] = undefined;
return list;
} else if(i == list.length - 1) {
console.log("Passenger not found!");
}
}
}
return list;
}

33
Ø Supervised work
Fundamental concepts
ü Objects, values, and variables

ü Conditionals and loops

ü Built-in functions: prompt, alert, confirm, typeof

ü JavaScript in an HTML file

ü Function declarations

ü Using arrays in JavaScript

n Anonymous closures and augmentation

36
Inheritance
Clothing
- id: String
- description: String
- price: String

+ displayInformation( )

Hat Sock Pant Shirt


- colorCode: {'R', 'G', 'B'} - colorCode: {'R','G','B'} - size: Integer - size: { 'S', 'M', 'L' }
- gender: { 'M', 'F' } - colorCode: {'R','G','B'}
- colorCode: { 'B', 'T' }
+ displayInformation() + displayInformation() + displayInformation() + displayInformation()

37
Anonymous closures
var CLOTHING = (function( d, p ) {
CLOTHING.counter = (++CLOTHING.counter || 1);
var id = CLOTHING.counter;
var description = d;
var price = p;
return {
getID: function() { return id; },
getDescription: function() { return description; },
getPrice: function() { return price; },
displayInformation: function() {
console.log('Clothing id: ' + id);
console.log('Clothing description: ' + description);
console.log('Clothing price: ' + price);
}
}
});
38
Augmentation (1)
var SHIRT = (function( d, p, s, c ) {
var shirt = CLOTHING(d, p);
var size = (s == 'S' || s == 'M' || s == 'L') ? s : 'U';
var colorCode = (c == 'R' || c == 'G' || c == 'B') ? c : 'U';
shirt.getSize = function() { return size; };
shirt.getColorCode = function() { return colorCode; };
shirt.displayInformation = function() {
console.log('Shirt id: ' + shirt.getID());
console.log('Shirt description: ' + shirt.getDescription());
console.log('Shirt price: ' + shirt.getPrice());
console.log('Shirt size: ' + size);
console.log('Shirt color: ' + colorCode);
};
return shirt;
});

39
Augmentation (2)
var HAT = (function( d, p, c ) {
var hat = CLOTHING(d, p);
var colorCode = (c == 'R' || c == 'G' || c == 'B') ? c : 'U';
hat.getColorCode = function() { return colorCode; };
hat.displayInformation = function() {
console.log('Hat id: ' + hat.getID());
console.log('Hat description: ' + hat.getDescription());
console.log('Hat price: ' + hat.getPrice());
console.log('Hat color: ' + colorCode);
};
return hat;
});
var shirt = SHIRT( 'T-Shirt', 19.99, 'M', 'R' );

var hat = HAT( 'Adventure Hat', 199.99, 'R' );

40
Agenda
ü Data/document models and languages

ü Programming Web based applications using JavaScript:


¨ Fundamental concepts
¨ Forest of function expressions
¨ JavaScript best practices

n The client, the Web server, and the storage support

41
HTML local storage
n Web applications can store data locally within the user's browser:
¨ Before HTML5, application data had to be stored in cookies, included in every
server request
¨ Unlike cookies, the storage limit is far larger (at least 5MB) and information is
never transferred to the server
¨ Local storage is more secure, and large amounts of data can be stored locally,
without affecting website performance

n HTML local storage provides two objects for storing data on the
client*:
¨ window.localStorage: It stores data with no expiration date
¨ window.sessionStorage: It stores data for one session (data is lost when the
browser tab is closed

* See examples at http://www.w3schools.com/html/html5_webstorage.asp.

42

You might also like