SlideShare uma empresa Scribd logo
1 de 86
Baixar para ler offline
Gran Sasso Science Institute
Ivano Malavolta
JavaScript
Roadmap
JavaScriptbasics
JavaScriptevent loop
Ajax and promises
DOM interaction
JavaScriptobject orientation
Web Workers
Useful Microframeworks
JavaScript
JavaScriptisTHE scriptinglanguage
Born in 1995, it is now one of the most famous programming
languages
Heavilyused by all majorplayersin web and mobile development
….and remember this…
JavaScriptHASNOTHING TO DO WITH Java!!
Essentials
JavaScriptisthe programming code thatcan be inserted into
HTML pages
àcan react to events in the DOM
àcan modify the DOM
Interpreted language
àsee the eval() function
The HTML5 standardis adding new APIs to JavaScript
Can you list some of them?
Essentials
We can use the <script>tag to insert JavaScriptcodeinto our
web app
<!DOCTYPE html>
<html>
<body>
<scriptsrc="myScript.js"></script>
</body>
</html>
If you wantto execute code when you need it,you have to
create a function
The code in myScriptis
executed immediately
We will use a module loader
to load JS
Expressions
An expression is any validunit of code thatresolves to a value
Four types of expressions:
• arithmetic:evaluatesto a number
• string: evaluatesto a sequence of chars
• logical:evaluates to true or false
• object: evaluatesto an object
Yes, JavaScriptisobject-
oriented
Statements
A JS program is composed of a set of statements, which can be:
• Conditional
– if
– switch
• Loop
– for
– while, do-while
– break, continue
– for..in
• Exception handling
– throw
– try, catch
– finally
I assume you all
know these
Operators on expressions
Operators performsome actions on expressions and may
produce other expressions as output
Five main types of operators:
• assignment
– x = x + y; x*= 3; x %= y, x = x & y
• comparison (alwaysreturn a logical value)
– x == 3; x != 5; x === y; 5 > 3
• arithmetic(alwaysreturna numericalvalue)
• logical
– && (AND), || (OR), ! (NOT)
• String
– + (stringconcatenation)
Special operators (1)
JavaScriptprovides the following special operators:
• Conditional operator
condition ? val1 : val2
• Commaoperator
– evaluatesboth of itsoperandsand returnsthe value of the second operand
• delete
– deletes an object, a property or an array element
delete window.obj
• in
– checks if a property exists in an object
var myCar = {make:’Opel’, model:’Corsa’, year:2014};
‘make’ in myCar; // returns true
Special operators (2)
• instanceof
– similar to the instanceOf keyword in Java
myObj instanceof Car; //returns true
• new
– creates an instance of an object
var myself = new Person(‘Ivano Malavolta’);
• this
– refers to the current object
this.name;
this[‘name’];
• typeof
– returns the type of anexpression
typeof myself.name; // returns string
Variables (1)
Variables are declared by using the keyword var
var magicNumber = 42;
var user = App.getCurrentUser();
var loggedUser = (user.isLogged())? user.name: undefined
If a variable has no value yetit evaluates to undefined
If a variable has not been defined an exception will be threw:
UncaughtReferenceError: c is not defined
Global variable: when it is declared OUTSIDEanyfunction
à available to anyother code within the app
Local variable: when it is declared INSIDEa function
Variables (2)
The scope of JavaScriptstatements is based on functions (not blocks)
If you declare a variable without the var keyword, you are creating a
global variable (!)
In the browser global variables can be accessed bywindow.varName
this works
Constants and Literals
• Array
– var bands = [‘NIN’, ‘Kraftwerk’, ‘Rammstein’];
• Boolean
– var logged= true; // false
• Integer and Floating point
– var age = 12;
– var PI = 3.14;
• String
– var hello = ‘hello’;
• Objects
– var band = {name: ‘TheSmiths’, founder: {name: ‘Steven’, surname:
‘Morrissey’}};
– band.name; // The Smiths
– band.founder[‘surname’]; // Morrissey
Function declarations
A function declaration is composed of:
• name
• parameters
• body
Primitive parameters are passed by value
Objects are passed byreference
A function is actually an expression:
This is an example of anonymousfunction
Function Calls
Functions can be called by referring to their name andpassing its
parameters
A function can produce a result by means of the return statement
Since function declarations are expressions, a function canbe declared
and executed all at once
Functional Programming
Functions can be passed as arguments to other functions, or canbe
produced as output of anotherfunction
function map(f,a) {
var result = [], i;
for(i=0; i !=a.length; i++) {
result[i] = f(a[i]);
}
return result;
}
map(function(x) {
return x*x*x;
}, [0,1,2,5,10]);
result?
Closures
A closure is a special kind of object consisting of:
• A function
• The function’s environment
– any local variables thatwere in-scopeat the time that the closurewas
created
http://goo.gl/Ya0be
Closures with the same function def
http://goo.gl/Ya0be
Closures with the same environment
http://goo.gl/Ya0be
wow... makeCounter looks like a class...
What do you think about changeBy?
Roadmap
JavaScriptbasics
JavaScriptevent loop
Ajax and promises
DOM interaction
JavaScriptobject orientation
Web Workers
Useful Microframeworks
JavaScript event loop
Confusion about JavaScript’s asynchronous eventmodel is quite common
Confusion leads to bugs, bugs lead to anger, and Yoda taughtus the rest....
http://goo.gl/g3xvY
First exploration
Let’s see this piece of code
http://goo.gl/g3xvY
for (var i = 1; i <= 3; i++) {
setTimeout(function(){
console.log(i);
}, 0);
};
Later we will see why
the result is like this
What if a rare event happened
between these two lines of code?
Second exploration
Let’s see this piece of code
http://goo.gl/g3xvY
var start = new Date;
setTimeout(function(){
var end = new Date;
console.log('Time elapsed:', end - start, 'ms');
}, 500);
while (new Date - start < 1000) {};
Hint
The setTimeout callbackcan’t fire untilthe
while loop has finished running.
JavaScript concurrency model
JavaScripthas a concurrencymodel based on an event loop
Intuitively, youcan consider as if yourcode is always running in a loop
like this:
runYourScript();
while (atLeastOneEventIsQueued) {
fireNextQueuedEvent();
};
The two previous examples make sense now?
JavaScript concurrency model
The JavaScript concurrencymodel is composed of three main entities
http://goo.gl/0zgXC
Stack
Function calls form a stack of frames
Each time a function f is called,
1. a frame f is created with its arguments and local variables
2. the frame f is pushed on top of the stack
3. all the instructions of the function f are executed
4. when the function f returns, its frame is popped out
The JavaScript engine executes all the frames until the stack is empty
http://goo.gl/0zgXC
Heap
The heap stores all the objects created during the execution of
JavaScriptfunctions
The heap is just a nameto denote a large mostly unstructured region of
memory
http://goo.gl/0zgXC
Queue
The queue contains a list of messages to be processed
Each message has an associated function callback
When the stack is empty:
1. the first message of the queue is taken out
2. its function callback is processed
– basically, a new stack frame is created for callback and it is processed
The message processing ends when the stack becomes empty
http://goo.gl/0zgXC
Important remarks about the queue
Each message is processed completely before anyother message is
considered
à when a function is running, it cannot be interrupted in any way
à it will always run until full completion
à it can modify data without race conditions
However, if a function takes too long, then it “stops” the app
Solutions:
• make message processing short
• split one message into several messages
• use web workers for multi-threading
http://goo.gl/0zgXC
Adding messages to the queue
In web browsers, a message is added when:
• an event occurs
• there is an event listener attached to the event
Examples of async functions generating messages in the queue:
• DOM interaction (touch, swipe, click…)
• timing functions (setTimeout, setInterval)
• I/O functions (read files, etc.)
• Ajax requests
If an event occurs (e.g. a touchevent), and there is no listener?
à the event is lost
http://goo.gl/0zgXC
Roadmap
JavaScriptbasics
JavaScriptevent loop
Ajax and promises
DOM interaction
JavaScriptobject orientation
Web Workers
Useful Microframeworks
Ajax
Ajax lets us fire requests from the browser to the server without
page reload
à you can update a partof the page while the user continues on
working
Basically,you can use Ajax requests to:
• load remote HTML
• get JSON data
Load JSON data
JSON is a lightweightalternativetoXML, where data is
structuredas plain JavaScriptobjects
Load JSON Data
Callback Functions
A callbackis a function that
1. is passed as an argument to anotherfunction
2. is executed afterits parentfunction has completed
– when an effect has been completed
– when an AJAX call has returned some data
$.get('myhtmlpage.html', myCallBack);
function myCallBack(data) {
// do something with data
}
myCallBackis invoked when the '$.get' is done getting the page
Promises
A promise is an object thatrepresents a task with:
1. two possible outcomes (success or failure)
2. callbacksthat fire when one outcome or the other has occurred
// with callbacks
$.get('/mydata', {
success: onSuccess,
failure: onFailure,
always: onAlways
});
// with promises
var promise = $.get('/mydata');
promise.done(onSuccess);
promise.fail(onFailure);
promise.always(onAlways);
Where is the difference?
Why promises?
If yourAjax request has multipleeffects (animation,other Ajax
requests, updatingthe DOM, etc.), you do not have to mix them with
the part of your app making the request
You can attachmultiple callbacksto the same request
For example, you may have a single callback for showing a spinner shared across
your app
You can derive new promises from existing ones
Encapsulation
Stacking
Promise derivation
Promise derivation
JQuery’s when method allowsyou to combine multiple promises
when acts as a logicalAND forpromise resolution and generates a
new promise that:
• is resolved as soon as all of the given Promises are resolved
• or it is rejected as soon as any one of the given Promises is rejected
var serverData = {};
var getting1 = $.get('/1')
.done(function(result) {serverData['1'] = result;});
var getting2 = $.get('/2')
.done(function(result) {serverData['2'] = result;});
$.when(getting1, getting2)
.done(function() {
// the GET information is now in serverData...
});
Roadmap
JavaScriptbasics
JavaScriptevent loop
Ajax and promises
DOM interaction
JavaScriptobject orientation
Web Workers
Useful Microframeworks
The DOM
DOM = Document Object Model
Every web page have a hierarchicalstructurein which every
element is containedinto another:its parent.
Text elements are particularsince they never havechildren
The DOM
In JavaScriptthedocument global variablestores a reference to
the object corresponding to the <html> tag
Every node of the DOM can be navigated:
document.body.parentNode
document.body.childNodes
document.body.firstChild
document.body.lastChild
document.body.nextSibling
document.body.previousSibling
Accessing the DOM
nodeName to get the name of the tag of a node:
document.body.firstChild.nodeName;
nodeValue to get the text of a text node:
document.body.firstChild.firstChild.nodeValue;
innerHTML to get/set the content of a node:
document.body.firstChild.innerHTML = "<div>Hello</div>";
getElementById to get a node by its ID:
document.getElementById("title");
getElementsByTagName to get a node by its type:
document.getElementsByTagName("DIV");
getElementsbyClassName to get a node by its class:
document.getElementsByClassName("listElement");
Modifying the DOM
createElement to create a new node:
var myDiv = document.createElement(”a");
createTextNode to create a new text node:
var textNode = document.createTextNode("Hello!");
setAttribute to setan attribute of a node:
myDiv.setAttribute("href", "http://www.google.it");
appendChildto putnew nodes into the DOM:
myDiv.appendChild(textNode);
document.body.appendChild(myDiv);
Events
Every time the user interacts withthe DOM, a set of events is
triggered in our JS application
We can listen to these events by means of registered
eventHandlers
An eventHandleris a function automaticallycalledby the browser,
where data about the triggered event is availableas a parameter
Event handlers can be unregistered
Example
document.getElementbyId("myDiv").addEventListener(
"touchend", manageTouch, false);
function manageTouch(event) {
console.log("touched " + event.target);
}
name of the
event
callback
function
handle the event in the
capturephase
data aboutthe event
Event Bubbling & capturing
When an event is triggeredin the DOM,
it can be:
• capturedby allthe elements
containingthe targetelement
àevent capturing
• capturedfirst by the target
and then BUBBLE up through all
the HTML elements containing
the target à event bubbling
Event default behaviour
Each element in the DOM has a defaultbehaviour
ex. if you tapon an <a> element, it will make the browser to point to
another location
event.preventDefault();
Cancels the event if it is cancelable, withoutstopping further
propagationof the event
Usually,this is the last instructionof an eventhandler
Touch events
Touch events are triggered when the user touches the display
The event can describe one or more points of contact
Touches are represented by the Touch object
each touch is described by a position,size and shape, amount of
pressure, and targetelement.
Lists of touches are represented by TouchList objects
Touch events
Main attributesof a touch event:
• TouchEvent.touches
– a TouchList of Touches
• TouchEvent.type
– the type of touch
• TouchEvent.target
– the element in the DOM
• TouchEvent.changedTouches
– a TouchList of all the Touches changed between this event and the
previous one
touchstart
touchend
touchmove
touchenter
touchcancel
The Touch and TouchList objects
relativeto the
viewport
relativeto the
whole display
Roadmap
JavaScriptbasics
JavaScriptevent loop
Ajax and promises
DOM interaction
JavaScriptobject orientation
Web Workers
Useful Microframeworks
JavaScript objects
An object in JS can be seen as a map of key/valuepairs
• key: a JavaScriptstring
• value: anyJavaScriptvalue
Everythingin JavaScriptis an object, and basicallyall its operations
involvehash table lookups (which are very fast in our browsers!)
Object creation
In JavaScriptanobject can be created in two ways:
new-value creation object literalsyntax
var obj = new Object();
obj.name = "Ivano";
...
var obj = {
name: "Ivano",
surname: "Malavolta",
details: {
sex: "male",
address: ”via..."
}
}
These are semantically
equivalent
Object properties
In JavaScriptanobject propertycan be created in two ways:
dot notation array-likenotation
obj.name = ‘Ivano’;
var name = obj.name;
obj[‘name’] = ‘Ivano’;
var name = obj[‘name’];
These are semanticallyequivalenttoo
In the array-likenotation,the propertyis a string
à it can be computed dynamically
Object Orientation (1): the model
JavaScriptobject model is prototype-based, rather than class-based
No notion of class, everythingis an object
An object can be seen as a «template» for other objects, in this case it is
the prototypeof the other objects
à it defines an initial set of properties
The inheriting objects can specify their own properties
Object Orientation (2): class definitions
In JavaI can specify a Class. Itcan have special methods, Constructors,
which I execute in order to create instances of myclass.
In JavaScriptI directly define Constructor functions thatI call to create
myobject bymeans of the new keyword.
The new and this keywords
new is strongly related to 'this'.
It creates a brand new empty object,and then calls the function
specified, with 'this' set to that new object.
The functionspecified with 'this' does not returna value but
merely modifies the this object.It's new thatreturns the this
object to the callingsite.
Functions thatare designed to be called by 'new' are called
constructorfunctions.Common practise is to capitalisethese
functions as a reminder to call them with new.
http://goo.gl/jBTMWX
Object Orientation (3): inheritance
In JavaI can define a hierarchyof classes bydefining subclasses via the
extends keyword
In JavaScriptI can define a constructorfunction X, then I can say that an
object created with X acts as the prototypeof constructorfunction Y
à X is a supertype of Y
Object Orientation (4): methods
In JavaI can define methods in myclass and call them by referring to
specific instances.
In JavaScriptI can define properties which canbe functions, then I can
call them directly on the object being used
OO Summary
JavaScriptobject model is prototype-based, rather than class-based
see here:
http://jsfiddle.net/6kdBa/10/
Roadmap
JavaScriptbasics
JavaScriptevent loop
Ajax and promises
DOM interaction
JavaScriptobject orientation
Web Workers
Useful Microframeworks
Web Workers
Javascriptis a single-threaded language
à If a task takes a lot of time, users have to wait
Web Workersprovide background processing capabilitiesto web
applications
They typicallyrun on separate threads
à apps can take advantageof multicore CPUs
Web Workers
Web Workerscan be used to:
• prefetch datafrom the Web
• perform other ahead-of-timeoperations to provide a much
more livelyUI.
Web Workersare precious on mobile applicationsbecause they
usually need to load data over a potentiallyslow network
Web Workers
Any JS file can be launched as a worker
Example of Web Worker declaration:
var worker = new Worker(“worker.js”);
In order to be independent from other workers,each worker
script cannotaccess:
– the DOM
– the global window object
• (each web worker has its own self global object)
Web Workers concurrency model
A web worker has its own
• stack,
• heap
• message queue
Two distinctruntimes can only communicatethrough sending
messages via the postMessage method
This method adds a message to the other runtimeif the latter
listens to message events.
Web Workers
The main JS script can communicatewith workers via
postMessage() calls:
$(‘#button’).click(function(event) {
$(‘#output’).html(“starting”);
worker.postMessage(“start”);
});
worker.onmessage = function(event) {
$(‘#output’).html(event.data);
}
Web Workers
The web workerscript can post back messages to the main script:
self.onmessage = function(event) {
if(event.data === “start”) {
var result;
// do something with result
self.postMessage(result);
}
}
Roadmap
JavaScriptbasics
JavaScriptevent loop
Ajax and promises
DOM interaction
JavaScriptobject orientation
Web Workers
Useful Microframeworks
Zepto
The only relevantdownside of jQuery is about
PERFORMANCE
However,
1. it is not verynoticeable in currentclass-A mobile devices
2. You can use mobile-suited alternativestojQuery:
Zepto
The goal is to havea ~5-10k modular librarythatexecutes fast,
with a familiarAPI (jQuery)
It can be seen as a
mini-jQuery
withoutsupport for
older browsers
Zepto Modules
Zepto Usage
Simplyreplace the reference to jQuery withthe one to Zepto
Underscore.js
A utilitylibraryfor JavaScriptthatprovidessupport for the usual
functionalsuspects (each, map, reduce, filter...)
It provides low-level utilitiesin the followingcategories:
• Collections
• Arrays
• Objects
• Functions
• Utilities
http://documentcloud.github.com/underscore/
iceCream
Minimal grid system for yourlayouts,pure CSS3 only
https://github.com/html5-ninja/icecream
iceCream
Ratchet
It provides the basic building blocks for realizingwell-known
mobile design patterns
Examples:
• Nav bars
• Title bars
• Lists
• Toggles
• Cards
• Popovers
• Sliders
• …
http://goratchet.com
Ratchet examples
Ratchet examples
Ratchet examples
Spin JS
It allows you to dynamicallycreate a spinning loading indicator
Pure CSSà resolution-independent
http://fgnass.github.io/spin.js/
Spin JS
Frameworks
jQueryMobile,jQuery, etc. are beautifullibraries…
However they may impactthe performance of your app
à Use a frameworkonly when it is necessary
– Don’t use jQueryonly because of the $(‘selector’) syntax!
Solution
• build your own micro-framework
• cut out Cordovaplugins you do not use
• use micro-frameworks(http://microjs.com)
A final note
JavaScriptallowsyouto do the same thing in many ways
In order to make yourcode readable (and thus maintainable),you
have to:
• follow as mush as possible known design patterns
– singleton, factory, etc.
• follow conventions
– https://github.com/rwaldron/idiomatic.js/
References
http://eloquentjavascript.net
https://developer.mozilla.org/en-US/docs/JavaScript
http://www.w3schools.com
http://www.microjs.com
Exercises
1. create a set of classes representing the domain of Loveitaly,
like:
– Product
– Seller
– User
2. develop a simple view for showing a list of products
1. HTML, CSS, JavaScript
2. user interactionmanagement
3. develop a view forshowing the details about a specific product
of Loveitaly
– here you have toreason about how toimplement a navigationinJavaScript

Mais conteúdo relacionado

Mais procurados

MVC & SQL_In_1_Hour
MVC & SQL_In_1_HourMVC & SQL_In_1_Hour
MVC & SQL_In_1_Hour
Dilip Patel
 

Mais procurados (20)

Rapi::Blog talk - TPC 2017
Rapi::Blog talk - TPC 2017Rapi::Blog talk - TPC 2017
Rapi::Blog talk - TPC 2017
 
Angular or Backbone: Go Mobile!
Angular or Backbone: Go Mobile!Angular or Backbone: Go Mobile!
Angular or Backbone: Go Mobile!
 
MVC Demystified: Essence of Ruby on Rails
MVC Demystified: Essence of Ruby on RailsMVC Demystified: Essence of Ruby on Rails
MVC Demystified: Essence of Ruby on Rails
 
HTML5: the new frontier of the web
HTML5: the new frontier of the webHTML5: the new frontier of the web
HTML5: the new frontier of the web
 
Angular - Chapter 6 - Firebase Integration
Angular - Chapter 6 - Firebase IntegrationAngular - Chapter 6 - Firebase Integration
Angular - Chapter 6 - Firebase Integration
 
C# Advanced L09-HTML5+ASP
C# Advanced L09-HTML5+ASPC# Advanced L09-HTML5+ASP
C# Advanced L09-HTML5+ASP
 
Angular - Chapter 3 - Components
Angular - Chapter 3 - ComponentsAngular - Chapter 3 - Components
Angular - Chapter 3 - Components
 
Modern development paradigms
Modern development paradigmsModern development paradigms
Modern development paradigms
 
Metaprogramming JavaScript
Metaprogramming  JavaScriptMetaprogramming  JavaScript
Metaprogramming JavaScript
 
Dart for Java Developers
Dart for Java DevelopersDart for Java Developers
Dart for Java Developers
 
Angular jS Introduction by Google
Angular jS Introduction by GoogleAngular jS Introduction by Google
Angular jS Introduction by Google
 
MVC & SQL_In_1_Hour
MVC & SQL_In_1_HourMVC & SQL_In_1_Hour
MVC & SQL_In_1_Hour
 
Fast mobile web apps
Fast mobile web appsFast mobile web apps
Fast mobile web apps
 
[2015/2016] Apache Cordova
[2015/2016] Apache Cordova[2015/2016] Apache Cordova
[2015/2016] Apache Cordova
 
Speed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSocketsSpeed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSockets
 
Mvc4
Mvc4Mvc4
Mvc4
 
Sightly - AEM6 UI Development using JS and JAVA
Sightly - AEM6 UI Development using JS and JAVASightly - AEM6 UI Development using JS and JAVA
Sightly - AEM6 UI Development using JS and JAVA
 
Javascript
JavascriptJavascript
Javascript
 
Aem best practices
Aem best practicesAem best practices
Aem best practices
 
Building search app with ElasticSearch
Building search app with ElasticSearchBuilding search app with ElasticSearch
Building search app with ElasticSearch
 

Destaque

Destaque (20)

The road ahead for architectural languages [ACVI 2016]
The road ahead for architectural languages [ACVI 2016]The road ahead for architectural languages [ACVI 2016]
The road ahead for architectural languages [ACVI 2016]
 
[2015/2016] Apache Cordova APIs
[2015/2016] Apache Cordova APIs[2015/2016] Apache Cordova APIs
[2015/2016] Apache Cordova APIs
 
[2015/2016] The REST architectural style
[2015/2016] The REST architectural style[2015/2016] The REST architectural style
[2015/2016] The REST architectural style
 
[2015/2016] Mobile thinking
[2015/2016] Mobile thinking[2015/2016] Mobile thinking
[2015/2016] Mobile thinking
 
[2015/2016] Geolocation and mapping
[2015/2016] Geolocation and mapping[2015/2016] Geolocation and mapping
[2015/2016] Geolocation and mapping
 
[2015/2016] User-centred design
[2015/2016] User-centred design[2015/2016] User-centred design
[2015/2016] User-centred design
 
SKA Systems Engineering: from PDR to Construction
SKA Systems Engineering: from PDR to ConstructionSKA Systems Engineering: from PDR to Construction
SKA Systems Engineering: from PDR to Construction
 
[2015/2016] Software systems engineering PRINCIPLES
[2015/2016] Software systems engineering PRINCIPLES[2015/2016] Software systems engineering PRINCIPLES
[2015/2016] Software systems engineering PRINCIPLES
 
[2016/2017] RESEARCH in software engineering
[2016/2017] RESEARCH in software engineering[2016/2017] RESEARCH in software engineering
[2016/2017] RESEARCH in software engineering
 
[2015/2016] Local data storage for web-based mobile apps
[2015/2016] Local data storage for web-based mobile apps[2015/2016] Local data storage for web-based mobile apps
[2015/2016] Local data storage for web-based mobile apps
 
[2015/2016] Modern development paradigms
[2015/2016] Modern development paradigms[2015/2016] Modern development paradigms
[2015/2016] Modern development paradigms
 
[2015/2016] AADL (Architecture Analysis and Design Language)
[2015/2016] AADL (Architecture Analysis and Design Language)[2015/2016] AADL (Architecture Analysis and Design Language)
[2015/2016] AADL (Architecture Analysis and Design Language)
 
[2015/2016] Introduction to software architecture
[2015/2016] Introduction to software architecture[2015/2016] Introduction to software architecture
[2015/2016] Introduction to software architecture
 
[2015/2016] HTML5 and CSS3 Refresher
[2015/2016] HTML5 and CSS3 Refresher[2015/2016] HTML5 and CSS3 Refresher
[2015/2016] HTML5 and CSS3 Refresher
 
Web-based Hybrid Mobile Apps: State of the Practice and Research opportunitie...
Web-based Hybrid Mobile Apps: State of the Practice and Research opportunitie...Web-based Hybrid Mobile Apps: State of the Practice and Research opportunitie...
Web-based Hybrid Mobile Apps: State of the Practice and Research opportunitie...
 
Leveraging Web Analytics for Automatically Generating Mobile Navigation Model...
Leveraging Web Analytics for Automatically Generating Mobile Navigation Model...Leveraging Web Analytics for Automatically Generating Mobile Navigation Model...
Leveraging Web Analytics for Automatically Generating Mobile Navigation Model...
 
[2015/2016] User experience design of mobil apps
[2015/2016] User experience design of mobil apps[2015/2016] User experience design of mobil apps
[2015/2016] User experience design of mobil apps
 
Design patterns for mobile apps
Design patterns for mobile appsDesign patterns for mobile apps
Design patterns for mobile apps
 
[2016/2017] Modern development paradigms
[2016/2017] Modern development paradigms [2016/2017] Modern development paradigms
[2016/2017] Modern development paradigms
 
[2016/2017] AADL (Architecture Analysis and Design Language)
[2016/2017] AADL (Architecture Analysis and Design Language)[2016/2017] AADL (Architecture Analysis and Design Language)
[2016/2017] AADL (Architecture Analysis and Design Language)
 

Semelhante a [2015/2016] JavaScript

WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
Fabio Franzini
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David Padbury
 

Semelhante a [2015/2016] JavaScript (20)

JavaScript for real men
JavaScript for real menJavaScript for real men
JavaScript for real men
 
Wt unit 5
Wt unit 5Wt unit 5
Wt unit 5
 
oojs
oojsoojs
oojs
 
Javascript Workshop
Javascript WorkshopJavascript Workshop
Javascript Workshop
 
React native
React nativeReact native
React native
 
Module design pattern i.e. express js
Module design pattern i.e. express jsModule design pattern i.e. express js
Module design pattern i.e. express js
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
 
How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design Patterns
 
Understanding Framework Architecture using Eclipse
Understanding Framework Architecture using EclipseUnderstanding Framework Architecture using Eclipse
Understanding Framework Architecture using Eclipse
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
Intro to ES6 and why should you bother !
Intro to ES6 and why should you bother !Intro to ES6 and why should you bother !
Intro to ES6 and why should you bother !
 
A First Date With Scala
A First Date With ScalaA First Date With Scala
A First Date With Scala
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
 
Javascript internals
Javascript internalsJavascript internals
Javascript internals
 
JS basics
JS basicsJS basics
JS basics
 
React Basic and Advance || React Basic
React Basic and Advance   || React BasicReact Basic and Advance   || React Basic
React Basic and Advance || React Basic
 
ES6 metaprogramming unleashed
ES6 metaprogramming unleashedES6 metaprogramming unleashed
ES6 metaprogramming unleashed
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
JS Essence
JS EssenceJS Essence
JS Essence
 

Mais de Ivano Malavolta

Mais de Ivano Malavolta (20)

Conducting Experiments on the Software Architecture of Robotic Systems (QRARS...
Conducting Experiments on the Software Architecture of Robotic Systems (QRARS...Conducting Experiments on the Software Architecture of Robotic Systems (QRARS...
Conducting Experiments on the Software Architecture of Robotic Systems (QRARS...
 
The H2020 experience
The H2020 experienceThe H2020 experience
The H2020 experience
 
The Green Lab - Research cocktail @Vrije Universiteit Amsterdam (October 2020)
The Green Lab - Research cocktail  @Vrije Universiteit Amsterdam (October 2020)The Green Lab - Research cocktail  @Vrije Universiteit Amsterdam (October 2020)
The Green Lab - Research cocktail @Vrije Universiteit Amsterdam (October 2020)
 
Software sustainability and Green IT
Software sustainability and Green ITSoftware sustainability and Green IT
Software sustainability and Green IT
 
Navigation-aware and Personalized Prefetching of Network Requests in Android ...
Navigation-aware and Personalized Prefetching of Network Requests in Android ...Navigation-aware and Personalized Prefetching of Network Requests in Android ...
Navigation-aware and Personalized Prefetching of Network Requests in Android ...
 
How Maintainability Issues of Android Apps Evolve [ICSME 2018]
How Maintainability Issues of Android Apps Evolve [ICSME 2018]How Maintainability Issues of Android Apps Evolve [ICSME 2018]
How Maintainability Issues of Android Apps Evolve [ICSME 2018]
 
Collaborative Model-Driven Software Engineering: a Classification Framework a...
Collaborative Model-Driven Software Engineering: a Classification Framework a...Collaborative Model-Driven Software Engineering: a Classification Framework a...
Collaborative Model-Driven Software Engineering: a Classification Framework a...
 
Experimenting on Mobile Apps Quality - a tale about Energy, Performance, and ...
Experimenting on Mobile Apps Quality - a tale about Energy, Performance, and ...Experimenting on Mobile Apps Quality - a tale about Energy, Performance, and ...
Experimenting on Mobile Apps Quality - a tale about Energy, Performance, and ...
 
Modeling objects interaction via UML sequence diagrams [Software Design] [Com...
Modeling objects interaction via UML sequence diagrams [Software Design] [Com...Modeling objects interaction via UML sequence diagrams [Software Design] [Com...
Modeling objects interaction via UML sequence diagrams [Software Design] [Com...
 
Modeling behaviour via UML state machines [Software Design] [Computer Science...
Modeling behaviour via UML state machines [Software Design] [Computer Science...Modeling behaviour via UML state machines [Software Design] [Computer Science...
Modeling behaviour via UML state machines [Software Design] [Computer Science...
 
Object-oriented design patterns in UML [Software Design] [Computer Science] [...
Object-oriented design patterns in UML [Software Design] [Computer Science] [...Object-oriented design patterns in UML [Software Design] [Computer Science] [...
Object-oriented design patterns in UML [Software Design] [Computer Science] [...
 
Structure modeling with UML [Software Design] [Computer Science] [Vrije Unive...
Structure modeling with UML [Software Design] [Computer Science] [Vrije Unive...Structure modeling with UML [Software Design] [Computer Science] [Vrije Unive...
Structure modeling with UML [Software Design] [Computer Science] [Vrije Unive...
 
Requirements engineering with UML [Software Design] [Computer Science] [Vrije...
Requirements engineering with UML [Software Design] [Computer Science] [Vrije...Requirements engineering with UML [Software Design] [Computer Science] [Vrije...
Requirements engineering with UML [Software Design] [Computer Science] [Vrije...
 
Modeling and abstraction, software development process [Software Design] [Com...
Modeling and abstraction, software development process [Software Design] [Com...Modeling and abstraction, software development process [Software Design] [Com...
Modeling and abstraction, software development process [Software Design] [Com...
 
[2017/2018] Agile development
[2017/2018] Agile development[2017/2018] Agile development
[2017/2018] Agile development
 
Reconstructing microservice-based architectures
Reconstructing microservice-based architecturesReconstructing microservice-based architectures
Reconstructing microservice-based architectures
 
[2017/2018] AADL - Architecture Analysis and Design Language
[2017/2018] AADL - Architecture Analysis and Design Language[2017/2018] AADL - Architecture Analysis and Design Language
[2017/2018] AADL - Architecture Analysis and Design Language
 
[2017/2018] Architectural languages
[2017/2018] Architectural languages[2017/2018] Architectural languages
[2017/2018] Architectural languages
 
[2017/2018] Introduction to Software Architecture
[2017/2018] Introduction to Software Architecture[2017/2018] Introduction to Software Architecture
[2017/2018] Introduction to Software Architecture
 
[2017/2018] RESEARCH in software engineering
[2017/2018] RESEARCH in software engineering[2017/2018] RESEARCH in software engineering
[2017/2018] RESEARCH in software engineering
 

Último

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Último (20)

Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 

[2015/2016] JavaScript

  • 1. Gran Sasso Science Institute Ivano Malavolta JavaScript
  • 2. Roadmap JavaScriptbasics JavaScriptevent loop Ajax and promises DOM interaction JavaScriptobject orientation Web Workers Useful Microframeworks
  • 3. JavaScript JavaScriptisTHE scriptinglanguage Born in 1995, it is now one of the most famous programming languages Heavilyused by all majorplayersin web and mobile development ….and remember this… JavaScriptHASNOTHING TO DO WITH Java!!
  • 4. Essentials JavaScriptisthe programming code thatcan be inserted into HTML pages àcan react to events in the DOM àcan modify the DOM Interpreted language àsee the eval() function The HTML5 standardis adding new APIs to JavaScript Can you list some of them?
  • 5. Essentials We can use the <script>tag to insert JavaScriptcodeinto our web app <!DOCTYPE html> <html> <body> <scriptsrc="myScript.js"></script> </body> </html> If you wantto execute code when you need it,you have to create a function The code in myScriptis executed immediately We will use a module loader to load JS
  • 6. Expressions An expression is any validunit of code thatresolves to a value Four types of expressions: • arithmetic:evaluatesto a number • string: evaluatesto a sequence of chars • logical:evaluates to true or false • object: evaluatesto an object Yes, JavaScriptisobject- oriented
  • 7. Statements A JS program is composed of a set of statements, which can be: • Conditional – if – switch • Loop – for – while, do-while – break, continue – for..in • Exception handling – throw – try, catch – finally I assume you all know these
  • 8. Operators on expressions Operators performsome actions on expressions and may produce other expressions as output Five main types of operators: • assignment – x = x + y; x*= 3; x %= y, x = x & y • comparison (alwaysreturn a logical value) – x == 3; x != 5; x === y; 5 > 3 • arithmetic(alwaysreturna numericalvalue) • logical – && (AND), || (OR), ! (NOT) • String – + (stringconcatenation)
  • 9. Special operators (1) JavaScriptprovides the following special operators: • Conditional operator condition ? val1 : val2 • Commaoperator – evaluatesboth of itsoperandsand returnsthe value of the second operand • delete – deletes an object, a property or an array element delete window.obj • in – checks if a property exists in an object var myCar = {make:’Opel’, model:’Corsa’, year:2014}; ‘make’ in myCar; // returns true
  • 10. Special operators (2) • instanceof – similar to the instanceOf keyword in Java myObj instanceof Car; //returns true • new – creates an instance of an object var myself = new Person(‘Ivano Malavolta’); • this – refers to the current object this.name; this[‘name’]; • typeof – returns the type of anexpression typeof myself.name; // returns string
  • 11. Variables (1) Variables are declared by using the keyword var var magicNumber = 42; var user = App.getCurrentUser(); var loggedUser = (user.isLogged())? user.name: undefined If a variable has no value yetit evaluates to undefined If a variable has not been defined an exception will be threw: UncaughtReferenceError: c is not defined Global variable: when it is declared OUTSIDEanyfunction à available to anyother code within the app Local variable: when it is declared INSIDEa function
  • 12. Variables (2) The scope of JavaScriptstatements is based on functions (not blocks) If you declare a variable without the var keyword, you are creating a global variable (!) In the browser global variables can be accessed bywindow.varName this works
  • 13.
  • 14. Constants and Literals • Array – var bands = [‘NIN’, ‘Kraftwerk’, ‘Rammstein’]; • Boolean – var logged= true; // false • Integer and Floating point – var age = 12; – var PI = 3.14; • String – var hello = ‘hello’; • Objects – var band = {name: ‘TheSmiths’, founder: {name: ‘Steven’, surname: ‘Morrissey’}}; – band.name; // The Smiths – band.founder[‘surname’]; // Morrissey
  • 15. Function declarations A function declaration is composed of: • name • parameters • body Primitive parameters are passed by value Objects are passed byreference A function is actually an expression: This is an example of anonymousfunction
  • 16. Function Calls Functions can be called by referring to their name andpassing its parameters A function can produce a result by means of the return statement Since function declarations are expressions, a function canbe declared and executed all at once
  • 17. Functional Programming Functions can be passed as arguments to other functions, or canbe produced as output of anotherfunction function map(f,a) { var result = [], i; for(i=0; i !=a.length; i++) { result[i] = f(a[i]); } return result; } map(function(x) { return x*x*x; }, [0,1,2,5,10]); result?
  • 18. Closures A closure is a special kind of object consisting of: • A function • The function’s environment – any local variables thatwere in-scopeat the time that the closurewas created http://goo.gl/Ya0be
  • 19. Closures with the same function def http://goo.gl/Ya0be
  • 20. Closures with the same environment http://goo.gl/Ya0be wow... makeCounter looks like a class... What do you think about changeBy?
  • 21. Roadmap JavaScriptbasics JavaScriptevent loop Ajax and promises DOM interaction JavaScriptobject orientation Web Workers Useful Microframeworks
  • 22. JavaScript event loop Confusion about JavaScript’s asynchronous eventmodel is quite common Confusion leads to bugs, bugs lead to anger, and Yoda taughtus the rest.... http://goo.gl/g3xvY
  • 23. First exploration Let’s see this piece of code http://goo.gl/g3xvY for (var i = 1; i <= 3; i++) { setTimeout(function(){ console.log(i); }, 0); }; Later we will see why the result is like this What if a rare event happened between these two lines of code?
  • 24. Second exploration Let’s see this piece of code http://goo.gl/g3xvY var start = new Date; setTimeout(function(){ var end = new Date; console.log('Time elapsed:', end - start, 'ms'); }, 500); while (new Date - start < 1000) {}; Hint The setTimeout callbackcan’t fire untilthe while loop has finished running.
  • 25. JavaScript concurrency model JavaScripthas a concurrencymodel based on an event loop Intuitively, youcan consider as if yourcode is always running in a loop like this: runYourScript(); while (atLeastOneEventIsQueued) { fireNextQueuedEvent(); }; The two previous examples make sense now?
  • 26. JavaScript concurrency model The JavaScript concurrencymodel is composed of three main entities http://goo.gl/0zgXC
  • 27. Stack Function calls form a stack of frames Each time a function f is called, 1. a frame f is created with its arguments and local variables 2. the frame f is pushed on top of the stack 3. all the instructions of the function f are executed 4. when the function f returns, its frame is popped out The JavaScript engine executes all the frames until the stack is empty http://goo.gl/0zgXC
  • 28. Heap The heap stores all the objects created during the execution of JavaScriptfunctions The heap is just a nameto denote a large mostly unstructured region of memory http://goo.gl/0zgXC
  • 29. Queue The queue contains a list of messages to be processed Each message has an associated function callback When the stack is empty: 1. the first message of the queue is taken out 2. its function callback is processed – basically, a new stack frame is created for callback and it is processed The message processing ends when the stack becomes empty http://goo.gl/0zgXC
  • 30. Important remarks about the queue Each message is processed completely before anyother message is considered à when a function is running, it cannot be interrupted in any way à it will always run until full completion à it can modify data without race conditions However, if a function takes too long, then it “stops” the app Solutions: • make message processing short • split one message into several messages • use web workers for multi-threading http://goo.gl/0zgXC
  • 31. Adding messages to the queue In web browsers, a message is added when: • an event occurs • there is an event listener attached to the event Examples of async functions generating messages in the queue: • DOM interaction (touch, swipe, click…) • timing functions (setTimeout, setInterval) • I/O functions (read files, etc.) • Ajax requests If an event occurs (e.g. a touchevent), and there is no listener? à the event is lost http://goo.gl/0zgXC
  • 32. Roadmap JavaScriptbasics JavaScriptevent loop Ajax and promises DOM interaction JavaScriptobject orientation Web Workers Useful Microframeworks
  • 33. Ajax Ajax lets us fire requests from the browser to the server without page reload à you can update a partof the page while the user continues on working Basically,you can use Ajax requests to: • load remote HTML • get JSON data
  • 34. Load JSON data JSON is a lightweightalternativetoXML, where data is structuredas plain JavaScriptobjects
  • 36. Callback Functions A callbackis a function that 1. is passed as an argument to anotherfunction 2. is executed afterits parentfunction has completed – when an effect has been completed – when an AJAX call has returned some data $.get('myhtmlpage.html', myCallBack); function myCallBack(data) { // do something with data } myCallBackis invoked when the '$.get' is done getting the page
  • 37. Promises A promise is an object thatrepresents a task with: 1. two possible outcomes (success or failure) 2. callbacksthat fire when one outcome or the other has occurred // with callbacks $.get('/mydata', { success: onSuccess, failure: onFailure, always: onAlways }); // with promises var promise = $.get('/mydata'); promise.done(onSuccess); promise.fail(onFailure); promise.always(onAlways); Where is the difference?
  • 38. Why promises? If yourAjax request has multipleeffects (animation,other Ajax requests, updatingthe DOM, etc.), you do not have to mix them with the part of your app making the request You can attachmultiple callbacksto the same request For example, you may have a single callback for showing a spinner shared across your app You can derive new promises from existing ones Encapsulation Stacking Promise derivation
  • 39. Promise derivation JQuery’s when method allowsyou to combine multiple promises when acts as a logicalAND forpromise resolution and generates a new promise that: • is resolved as soon as all of the given Promises are resolved • or it is rejected as soon as any one of the given Promises is rejected var serverData = {}; var getting1 = $.get('/1') .done(function(result) {serverData['1'] = result;}); var getting2 = $.get('/2') .done(function(result) {serverData['2'] = result;}); $.when(getting1, getting2) .done(function() { // the GET information is now in serverData... });
  • 40. Roadmap JavaScriptbasics JavaScriptevent loop Ajax and promises DOM interaction JavaScriptobject orientation Web Workers Useful Microframeworks
  • 41. The DOM DOM = Document Object Model Every web page have a hierarchicalstructurein which every element is containedinto another:its parent. Text elements are particularsince they never havechildren
  • 42. The DOM In JavaScriptthedocument global variablestores a reference to the object corresponding to the <html> tag Every node of the DOM can be navigated: document.body.parentNode document.body.childNodes document.body.firstChild document.body.lastChild document.body.nextSibling document.body.previousSibling
  • 43. Accessing the DOM nodeName to get the name of the tag of a node: document.body.firstChild.nodeName; nodeValue to get the text of a text node: document.body.firstChild.firstChild.nodeValue; innerHTML to get/set the content of a node: document.body.firstChild.innerHTML = "<div>Hello</div>"; getElementById to get a node by its ID: document.getElementById("title"); getElementsByTagName to get a node by its type: document.getElementsByTagName("DIV"); getElementsbyClassName to get a node by its class: document.getElementsByClassName("listElement");
  • 44. Modifying the DOM createElement to create a new node: var myDiv = document.createElement(”a"); createTextNode to create a new text node: var textNode = document.createTextNode("Hello!"); setAttribute to setan attribute of a node: myDiv.setAttribute("href", "http://www.google.it"); appendChildto putnew nodes into the DOM: myDiv.appendChild(textNode); document.body.appendChild(myDiv);
  • 45. Events Every time the user interacts withthe DOM, a set of events is triggered in our JS application We can listen to these events by means of registered eventHandlers An eventHandleris a function automaticallycalledby the browser, where data about the triggered event is availableas a parameter Event handlers can be unregistered
  • 46. Example document.getElementbyId("myDiv").addEventListener( "touchend", manageTouch, false); function manageTouch(event) { console.log("touched " + event.target); } name of the event callback function handle the event in the capturephase data aboutthe event
  • 47. Event Bubbling & capturing When an event is triggeredin the DOM, it can be: • capturedby allthe elements containingthe targetelement àevent capturing • capturedfirst by the target and then BUBBLE up through all the HTML elements containing the target à event bubbling
  • 48. Event default behaviour Each element in the DOM has a defaultbehaviour ex. if you tapon an <a> element, it will make the browser to point to another location event.preventDefault(); Cancels the event if it is cancelable, withoutstopping further propagationof the event Usually,this is the last instructionof an eventhandler
  • 49. Touch events Touch events are triggered when the user touches the display The event can describe one or more points of contact Touches are represented by the Touch object each touch is described by a position,size and shape, amount of pressure, and targetelement. Lists of touches are represented by TouchList objects
  • 50. Touch events Main attributesof a touch event: • TouchEvent.touches – a TouchList of Touches • TouchEvent.type – the type of touch • TouchEvent.target – the element in the DOM • TouchEvent.changedTouches – a TouchList of all the Touches changed between this event and the previous one touchstart touchend touchmove touchenter touchcancel
  • 51. The Touch and TouchList objects relativeto the viewport relativeto the whole display
  • 52. Roadmap JavaScriptbasics JavaScriptevent loop Ajax and promises DOM interaction JavaScriptobject orientation Web Workers Useful Microframeworks
  • 53. JavaScript objects An object in JS can be seen as a map of key/valuepairs • key: a JavaScriptstring • value: anyJavaScriptvalue Everythingin JavaScriptis an object, and basicallyall its operations involvehash table lookups (which are very fast in our browsers!)
  • 54. Object creation In JavaScriptanobject can be created in two ways: new-value creation object literalsyntax var obj = new Object(); obj.name = "Ivano"; ... var obj = { name: "Ivano", surname: "Malavolta", details: { sex: "male", address: ”via..." } } These are semantically equivalent
  • 55. Object properties In JavaScriptanobject propertycan be created in two ways: dot notation array-likenotation obj.name = ‘Ivano’; var name = obj.name; obj[‘name’] = ‘Ivano’; var name = obj[‘name’]; These are semanticallyequivalenttoo In the array-likenotation,the propertyis a string à it can be computed dynamically
  • 56. Object Orientation (1): the model JavaScriptobject model is prototype-based, rather than class-based No notion of class, everythingis an object An object can be seen as a «template» for other objects, in this case it is the prototypeof the other objects à it defines an initial set of properties The inheriting objects can specify their own properties
  • 57. Object Orientation (2): class definitions In JavaI can specify a Class. Itcan have special methods, Constructors, which I execute in order to create instances of myclass. In JavaScriptI directly define Constructor functions thatI call to create myobject bymeans of the new keyword.
  • 58. The new and this keywords new is strongly related to 'this'. It creates a brand new empty object,and then calls the function specified, with 'this' set to that new object. The functionspecified with 'this' does not returna value but merely modifies the this object.It's new thatreturns the this object to the callingsite. Functions thatare designed to be called by 'new' are called constructorfunctions.Common practise is to capitalisethese functions as a reminder to call them with new. http://goo.gl/jBTMWX
  • 59. Object Orientation (3): inheritance In JavaI can define a hierarchyof classes bydefining subclasses via the extends keyword In JavaScriptI can define a constructorfunction X, then I can say that an object created with X acts as the prototypeof constructorfunction Y à X is a supertype of Y
  • 60. Object Orientation (4): methods In JavaI can define methods in myclass and call them by referring to specific instances. In JavaScriptI can define properties which canbe functions, then I can call them directly on the object being used
  • 61. OO Summary JavaScriptobject model is prototype-based, rather than class-based see here: http://jsfiddle.net/6kdBa/10/
  • 62. Roadmap JavaScriptbasics JavaScriptevent loop Ajax and promises DOM interaction JavaScriptobject orientation Web Workers Useful Microframeworks
  • 63. Web Workers Javascriptis a single-threaded language à If a task takes a lot of time, users have to wait Web Workersprovide background processing capabilitiesto web applications They typicallyrun on separate threads à apps can take advantageof multicore CPUs
  • 64. Web Workers Web Workerscan be used to: • prefetch datafrom the Web • perform other ahead-of-timeoperations to provide a much more livelyUI. Web Workersare precious on mobile applicationsbecause they usually need to load data over a potentiallyslow network
  • 65. Web Workers Any JS file can be launched as a worker Example of Web Worker declaration: var worker = new Worker(“worker.js”); In order to be independent from other workers,each worker script cannotaccess: – the DOM – the global window object • (each web worker has its own self global object)
  • 66. Web Workers concurrency model A web worker has its own • stack, • heap • message queue Two distinctruntimes can only communicatethrough sending messages via the postMessage method This method adds a message to the other runtimeif the latter listens to message events.
  • 67. Web Workers The main JS script can communicatewith workers via postMessage() calls: $(‘#button’).click(function(event) { $(‘#output’).html(“starting”); worker.postMessage(“start”); }); worker.onmessage = function(event) { $(‘#output’).html(event.data); }
  • 68. Web Workers The web workerscript can post back messages to the main script: self.onmessage = function(event) { if(event.data === “start”) { var result; // do something with result self.postMessage(result); } }
  • 69. Roadmap JavaScriptbasics JavaScriptevent loop Ajax and promises DOM interaction JavaScriptobject orientation Web Workers Useful Microframeworks
  • 70. Zepto The only relevantdownside of jQuery is about PERFORMANCE However, 1. it is not verynoticeable in currentclass-A mobile devices 2. You can use mobile-suited alternativestojQuery:
  • 71. Zepto The goal is to havea ~5-10k modular librarythatexecutes fast, with a familiarAPI (jQuery) It can be seen as a mini-jQuery withoutsupport for older browsers
  • 73. Zepto Usage Simplyreplace the reference to jQuery withthe one to Zepto
  • 74. Underscore.js A utilitylibraryfor JavaScriptthatprovidessupport for the usual functionalsuspects (each, map, reduce, filter...) It provides low-level utilitiesin the followingcategories: • Collections • Arrays • Objects • Functions • Utilities http://documentcloud.github.com/underscore/
  • 75. iceCream Minimal grid system for yourlayouts,pure CSS3 only https://github.com/html5-ninja/icecream
  • 77. Ratchet It provides the basic building blocks for realizingwell-known mobile design patterns Examples: • Nav bars • Title bars • Lists • Toggles • Cards • Popovers • Sliders • … http://goratchet.com
  • 81. Spin JS It allows you to dynamicallycreate a spinning loading indicator Pure CSSà resolution-independent http://fgnass.github.io/spin.js/
  • 83. Frameworks jQueryMobile,jQuery, etc. are beautifullibraries… However they may impactthe performance of your app à Use a frameworkonly when it is necessary – Don’t use jQueryonly because of the $(‘selector’) syntax! Solution • build your own micro-framework • cut out Cordovaplugins you do not use • use micro-frameworks(http://microjs.com)
  • 84. A final note JavaScriptallowsyouto do the same thing in many ways In order to make yourcode readable (and thus maintainable),you have to: • follow as mush as possible known design patterns – singleton, factory, etc. • follow conventions – https://github.com/rwaldron/idiomatic.js/
  • 86. Exercises 1. create a set of classes representing the domain of Loveitaly, like: – Product – Seller – User 2. develop a simple view for showing a list of products 1. HTML, CSS, JavaScript 2. user interactionmanagement 3. develop a view forshowing the details about a specific product of Loveitaly – here you have toreason about how toimplement a navigationinJavaScript