SlideShare a Scribd company logo
Event Driven
Javascript
federico.galassi@cleancode.it
slidehare.net/fgalassi
• Event driven programming
• Event driven javascript
• History of javascript design
Software
components
exchange
information
Producers
give
information
Consumers
take
information
Taxonomy of
interaction models
Who is the
producer ?
Known
Where’s Kenny?
Over There!
Unknown
Where’s Kenny?
Where’s Kenny?
Over There!
Who is the
producer ?
known unknown
How does
information flow ?
Pull
Where’s Kenny?
Over There!
Push
Let me know
where’s Kenny
Ok
... later ...
Hey! Over There!
How does
information flow ?
known unknown
pull
push
4 Models of
interaction
known unknown
pull
push
Request
Response
1.
Request
Response
//  method  invocation
weapon  =  armory.buy(“shuriken”)
kenny  =  cartman.findKenny()
kenny.kill(weapon)
SIMPLE
Request
Response
SIMPLE
SEQUENTIAL
Request
Response
SIMPLE
SEQUENTIAL
IMPERATIVE
Request
Response
HUMAN
Request
Response
SEQUENTIAL
IMPERATIVE
Request
Response
TIGHT
COUPLING
SEQUENTIAL
IMPERATIVE
Request
Response
TIGHT
COUPLING
INEFFICIENT
known unknown
pull
push
Request
Response
2.
Anonymous
Request
Response
Anonymous
Request Response
The system decouples
information and its owner
Anonymous
Request Response
load balancer
Anonymous
Request Response
FAILOVERalancer
Anonymous
Request Response
alancer FAILOVER
EXTENSIBLE
Anonymous
Request Response
SYSTEM
COMPLEXITY
known unknown
pull
push
Request
Response
3.
Anonymous
Request
Response
Callback
Callback
//  observer  pattern
cartman.findKenny(
    function(kenny)  {
        kenny.kill(weapon)
})
Don’t call us
We’ll call you
From Sequential
INPUT
STATE
COMPUTATION
OUTPUT
To State Machine
INPUT STATE A
OUTPUT
INPUT STATE B
INPUT STATE C
COMPUTATION
COMPUTATION
Callback
Relinquish control
Just in time is optimal
Callback
Consumer
Producers
Callback
efficiency
Callback
efficiencyEXPLICIT
CONTROL
FLOW
known unknown
pull
push
Request
Response
4.
Anonymous
Request
Response
Callback Event Driven
Callback +
Anonymous
Request Response
=
EVENTS
Home Automation
Example
EVENTS
FAILOVER +
EXTENSIBLE +
efficiency =
-------------------------------------
power
system
COMPLEXITY +
explicit
control flow =
-------------------------------------
chaos
REQUEST RESPONSE
CALLBACK
ANON.
REQUEST
RESPONSE
EVENTS
Expressive Power
Complexity
Javascript
is
event* driven
*technically callback driven
Not
Javascript
Fault
Not
Your
Fault
Just an
HARDER
problem
• Event driven programming
• Event driven javascript
• History of javascript design
In the old days...
Netscape Headquarters
May 1995
This guy had two
problems...
Brendan Eich
Creator of Javascript
1. The world is
Concurrent
... and so is
browser
Network Requests
User Input
LiveScript first shipped in betas of Netscape Navigator 2.0 in
September 1995
2. Very very very
short time
Be
Pragmatic
He could use
Threads ...
Real preemptive
concurrency
Threads
are
Evil
He could use
Coroutines ...
Emulated
cooperative
concurrency
needs a
complex
scheduler
He was a
functional
guy
Not concurrent
Take it easy
Just non-blocking
Callbacks
//  callbacks  give
//  non  linear  execution
wally.takeJob(function  work()  ...)
wally.getCoffee(function  drink()  ...)
//  ...  later  ...
//  first  drink  coffee
//  then  work
Simple event loop
//  make  it  look  concurrent
button.onclick(function()  {
...
})
UI update
Click handler
UI update
Click handler
Click handlerUI
event
queue
time
User click
Non-blocking I/O
//  network  async  api
xhr.onreadystatechange  =  function(){
...
})
//  DOM  manipulations  are  synchronous
//  but  in  memory  so  very  fast
div.innerHTML  =  “Hello”
Javascript won
But
sold its soul
for simplicity
One thread
=
Freeze
No Wait()
function  breakfast()  {
var  bacon  =  bacon()
var  juice  =  orangeJuice()
eat(bacon,  juice)
}
Simple sequential
function  bacon()  {
//  get  bacon
return  bacon
}
computation
function  breakfast()  {
var  bacon  =  bacon()
var  juice  =  orangeJuice()
eat(bacon,  juice)
}
function  bacon()  {
getBacon(function(bacon)  {
//  got  bacon
})
}
Async gets in
wrong
return what?
Break computation
function  breakfast()  {
      var  callback  =  function(bacon)  {
var  juice  =  getOrangeJuice()
eat(bacon,  juice)
}
bacon(callback)
}
function  bacon(callback)  {
//  get  bacon  async
callback(bacon)
}
rest of computation
computation
Break more
function  breakfast()  {
      var  callback  =  function(bacon)  {
var  callback  =  function(juice)  {
eat(bacon,  juice)
}
getOrangeJuice(callback)
}
bacon(callback)
}
rest of computation 1
computation
rest of computation 2
Continuation
Passing
Style
//  simple  sequential  computation
function  A()  {  return  B()  }
function  B()  {  return  C()  }
function  C()  {  return  value  }
A()
it’s Viral1
it’s Viral
//  C  becomes  async,  everything  becomes  async
function  A(callback)  {
B(function(value)  {  callback(value)  })
}
function  B(callback)  {
C(function(value)  {  callback(value)  })
}
function  C(callback)  {  callback(value)  }
A()
2
//  simple  sequential  sleep
sleep(3000)
doSomething()
sleepit’s Hard
//  not  so  simple  sleep
setTimeout(function()  {
doSomething()
},  3000)
sleepit’s Hard
//  simple  sequential  loop
images.forEach(function(url)
var  image  =  fetchImage(url)
image.show()
}
loopit’s Hard
//  fetchImage  is  async
images.forEach(function(url)
fetchImage(url,  function(image)  {
image.show()
})
}
loopit’s Hard
//  Show  them  in  the  right  order
function  processImage()  {
var  url  =  images.shift()
if  (url)  {
fetchImage(url,  function(image)  {
image.show()
processImage()
})
}
}
processImage()
loopit’s Hard
Javascript
sacrificed
convenience
for simplicity
... and it was the
right choice
• Event driven programming
• Event driven javascript
• History of javascript design
How can we
tame
complexity?
Add
Wait()
stupid!
Easy
//  simple  sequential  sleep  with  wait/resume
sleep(3000)
doSomething()
function  sleep(msec)  {
wait(
setTimeout(function()  {
resume()
},  msec)
)
}
sleep
Beautiful
Already done !
http://stratifiedjs.org/
//  write  sequential  logic
function  doOpsABC()  {
waitfor  {
var  x  =  doOpA()
}
and  {
var  y  =  doOpB()
}
return  doOpC(x,y)
}
Transform to
continuation
passing
style
http://nodejs.org/
//  synchronous  read
fs.read(path).wait()
Implement
coroutines
Back to
complexity
Jeremy Ashkenas - CoffeeScript
“I don't think we want to take CoffeeScript down that
path. Open the Pandora's box of injecting special
functions into the runtime, and ... suddenly you have to
worry about being orders of magnitude slower than
normal JS.”
“Case in point, Stratified JS:A virtuoso performance of
JavaScript compilation, but look at what it compiles into.”
https://github.com/jashkenas/coffee-script/issuesearch?state=closed&q=asynchronous#issue/350/comment/330116
Jeremy Ashkenas - CoffeeScript
var getDocument = function(){
waitfor(document) {
resume(db.get(id));
}
return document;
};
var getDocument;
__oni_rt.exec(__oni_rt.Seq(0,__oni_rt.Seq(0,__oni_rt.Nblock(
function(arguments){
getDocument=function (){
return __oni_rt.exec(__oni_rt.Seq(1,__oni_rt.Suspend(
function(arguments, resume){
return __oni_rt.exec(__oni_rt.Seq(0,__oni_rt.Fcall(0,__oni_rt.Nbl
function(arguments){
return resume;
}),__oni_rt.Nblock(function(arguments){
return db.get(id)
})
)),arguments,this)},
function() {
document=arguments[0];
}),__oni_rt.Fcall(0,__oni_rt.Return,__oni_rt.Nblock(
function(arguments){
return document;
})
)),arguments, this)};
}))), this.arguments, this);
“I will be removing wait() in the next release of Node.
It has already been removed from the documentation.”
“A proper implementation of wait() necessitates true
coroutines”
“This sort of mental complication is exactly what I'm
trying to avoid in Node.”
Ryan Dahl - node.js
http://groups.google.com/group/nodejs/msg/df199d233ff17efa
No wait()
Take it easy
Just control flow
Sequence
//  async  sequential  computation
sequence(get,  filter,  process)
function  get(resume)  {
$.get(url,  function(data)  {
resume(data)
})
}
function  filter(resume,  data)  {  ...  }
function  process(resume,  data)  {  ...  }
1
Sequence
//  async  sequential  computation
function  sequence()  {
var  steps  =  arguments.slice()
var  doStep  =  function(val)  {
var  next  =  steps.shift()
if  (next)  {
next.apply(null,  [doStep,  val])
}
}
doStep()
}
2
Functional
programming
first(fetchA,  fetchB,  fetchC,  callback)
every(checkA,  checkB,  checkC,  callback)
map(array,  mapper,  callback)
filter(array,  filter,  callback)
The road is
taking your
control flow
From imperative
//  complex  triple  click  event
var  clicks  =  0,  timeout  =  null
$(“button”).click(function()  {
clicks++
if  (clicks  ==  1)  {
timeout  =  setTimeout(function()  {
clicks  =  0
},  1000)
}
if  (clicks  ==  3)  {
clearTimeout(timeout)
clicks  =  0
$(this).trigger(“tripleclick”)
}
})
To declarative
$(button)
.on(“click”)
.times(3)
.within(“1  second”)
.trigger(“tripleclick”)
Questions?
federico.galassi@cleancode.it

More Related Content

KEY
Node.js 0.8 features
Nicholas McClay
 
PDF
Need for Async: Hot pursuit for scalable applications
Konrad Malawski
 
PDF
Beyond Phoenix
Gabriele Lana
 
PDF
Automation with Ansible and Containers
Rodolfo Carvalho
 
KEY
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
Tatsuhiko Miyagawa
 
PDF
ScalaSwarm 2017 Keynote: Tough this be madness yet theres method in't
Konrad Malawski
 
PDF
DevOps(4) : Ansible(2) - (MOSG)
Soshi Nemoto
 
PDF
A Taste of Clojure
David Leung
 
Node.js 0.8 features
Nicholas McClay
 
Need for Async: Hot pursuit for scalable applications
Konrad Malawski
 
Beyond Phoenix
Gabriele Lana
 
Automation with Ansible and Containers
Rodolfo Carvalho
 
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
Tatsuhiko Miyagawa
 
ScalaSwarm 2017 Keynote: Tough this be madness yet theres method in't
Konrad Malawski
 
DevOps(4) : Ansible(2) - (MOSG)
Soshi Nemoto
 
A Taste of Clojure
David Leung
 

What's hot (20)

PDF
Boom! Promises/A+ Was Born
Domenic Denicola
 
KEY
Plack - LPW 2009
Tatsuhiko Miyagawa
 
PDF
Play vs Rails
Daniel Cukier
 
PPTX
Javascript asynchronous
kang taehun
 
KEY
Intro to PSGI and Plack
Tatsuhiko Miyagawa
 
PPTX
Domains!
Domenic Denicola
 
PDF
Mobile Open Day: React Native: Crossplatform fast dive
epamspb
 
PDF
Scaling Ruby with Evented I/O - Ruby underground
Omer Gazit
 
PDF
Distributed Consensus A.K.A. "What do we eat for lunch?"
Konrad Malawski
 
KEY
Tatsumaki
Tatsuhiko Miyagawa
 
PDF
Building reactive distributed systems with Akka
Johan Andrén
 
PDF
Hopping in clouds: a tale of migration from one cloud provider to another
Michele Orselli
 
PDF
React Native Evening
Troy Miles
 
PDF
React Native in Production
Seokjun Kim
 
PDF
A Gentle Introduction to Event Loops
deepfountainconsulting
 
PDF
"Swoole: double troubles in c", Alexandr Vronskiy
Fwdays
 
PPTX
Real world functional reactive programming
Eric Polerecky
 
PDF
Containers & Dependency in Ember.js
Matthew Beale
 
PPTX
Node.js: A Guided Tour
cacois
 
PDF
Online game server on Akka.NET (NDC2016)
Esun Kim
 
Boom! Promises/A+ Was Born
Domenic Denicola
 
Plack - LPW 2009
Tatsuhiko Miyagawa
 
Play vs Rails
Daniel Cukier
 
Javascript asynchronous
kang taehun
 
Intro to PSGI and Plack
Tatsuhiko Miyagawa
 
Mobile Open Day: React Native: Crossplatform fast dive
epamspb
 
Scaling Ruby with Evented I/O - Ruby underground
Omer Gazit
 
Distributed Consensus A.K.A. "What do we eat for lunch?"
Konrad Malawski
 
Building reactive distributed systems with Akka
Johan Andrén
 
Hopping in clouds: a tale of migration from one cloud provider to another
Michele Orselli
 
React Native Evening
Troy Miles
 
React Native in Production
Seokjun Kim
 
A Gentle Introduction to Event Loops
deepfountainconsulting
 
"Swoole: double troubles in c", Alexandr Vronskiy
Fwdays
 
Real world functional reactive programming
Eric Polerecky
 
Containers & Dependency in Ember.js
Matthew Beale
 
Node.js: A Guided Tour
cacois
 
Online game server on Akka.NET (NDC2016)
Esun Kim
 
Ad

Viewers also liked (7)

PPT
Event+driven+programming key+features
Faisal Aziz
 
PPTX
Modeling Patterns for JavaScript Browser-Based Games
Ray Toal
 
PDF
Server Side Event Driven Programming
Kamal Hussain
 
PDF
Vim, the Way of the Keyboard
Federico Galassi
 
PDF
Marketing theo định hướng dữ liệu (Data-Driven) và Hệ thống quản trị khách hà...
ANTS
 
PPTX
Event driven programming amazeballs
MsWillcox
 
PDF
Bài 7: Danh sách liên kết (LINKED LIST) và tập hợp (SET) - Giáo trình FPT
MasterCode.vn
 
Event+driven+programming key+features
Faisal Aziz
 
Modeling Patterns for JavaScript Browser-Based Games
Ray Toal
 
Server Side Event Driven Programming
Kamal Hussain
 
Vim, the Way of the Keyboard
Federico Galassi
 
Marketing theo định hướng dữ liệu (Data-Driven) và Hệ thống quản trị khách hà...
ANTS
 
Event driven programming amazeballs
MsWillcox
 
Bài 7: Danh sách liên kết (LINKED LIST) và tập hợp (SET) - Giáo trình FPT
MasterCode.vn
 
Ad

Similar to Event Driven Javascript (20)

PDF
Event driven javascript
Francesca1980
 
PDF
Event driven javascript
Francesca1980
 
PDF
Douglas Crockford: Serversideness
WebExpo
 
PDF
The evolution of asynchronous JavaScript
Alessandro Cinelli (cirpo)
 
KEY
Playing With Fire - An Introduction to Node.js
Mike Hagedorn
 
PPTX
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Domenic Denicola
 
PDF
Asynchronous programming done right - Node.js
Piotr Pelczar
 
PPTX
Events for JavaScript event loop track.pptx
sontinenianuradha
 
PDF
The evolution of asynchronous javascript
Alessandro Cinelli (cirpo)
 
PPTX
Async Frontiers
Domenic Denicola
 
PPTX
Avoiding Callback Hell with Async.js
cacois
 
PDF
The art of concurrent programming
Iskren Chernev
 
PDF
The Evolution of Async-Programming (SD 2.0, JavaScript)
jeffz
 
PPTX
Node js for backend server development.
digitalindia1231
 
PDF
Understanding Asynchronous JavaScript
jnewmanux
 
PDF
Introduction to Node.js
Richard Lee
 
PDF
Intro to node.js - Ran Mizrahi (27/8/2014)
Ran Mizrahi
 
PDF
Intro to node.js - Ran Mizrahi (28/8/14)
Ran Mizrahi
 
PPTX
node.js workshop- JavaScript Async
Qiong Wu
 
ODP
Node js lecture
Darryl Sherman
 
Event driven javascript
Francesca1980
 
Event driven javascript
Francesca1980
 
Douglas Crockford: Serversideness
WebExpo
 
The evolution of asynchronous JavaScript
Alessandro Cinelli (cirpo)
 
Playing With Fire - An Introduction to Node.js
Mike Hagedorn
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Domenic Denicola
 
Asynchronous programming done right - Node.js
Piotr Pelczar
 
Events for JavaScript event loop track.pptx
sontinenianuradha
 
The evolution of asynchronous javascript
Alessandro Cinelli (cirpo)
 
Async Frontiers
Domenic Denicola
 
Avoiding Callback Hell with Async.js
cacois
 
The art of concurrent programming
Iskren Chernev
 
The Evolution of Async-Programming (SD 2.0, JavaScript)
jeffz
 
Node js for backend server development.
digitalindia1231
 
Understanding Asynchronous JavaScript
jnewmanux
 
Introduction to Node.js
Richard Lee
 
Intro to node.js - Ran Mizrahi (27/8/2014)
Ran Mizrahi
 
Intro to node.js - Ran Mizrahi (28/8/14)
Ran Mizrahi
 
node.js workshop- JavaScript Async
Qiong Wu
 
Node js lecture
Darryl Sherman
 

More from Federico Galassi (9)

PDF
The Strange World of Javascript and all its little Asynchronous Beasts
Federico Galassi
 
PDF
Javascript the New Parts v2
Federico Galassi
 
PDF
CouchApps: Requiem for Accidental Complexity
Federico Galassi
 
PDF
Please Don't Touch the Slow Parts V3
Federico Galassi
 
PDF
Javascript the New Parts
Federico Galassi
 
PDF
Please Don't Touch the Slow Parts V2
Federico Galassi
 
PDF
Please Don't Touch the Slow Parts
Federico Galassi
 
PDF
Javascript The Good Parts v2
Federico Galassi
 
PDF
Javascript The Good Parts
Federico Galassi
 
The Strange World of Javascript and all its little Asynchronous Beasts
Federico Galassi
 
Javascript the New Parts v2
Federico Galassi
 
CouchApps: Requiem for Accidental Complexity
Federico Galassi
 
Please Don't Touch the Slow Parts V3
Federico Galassi
 
Javascript the New Parts
Federico Galassi
 
Please Don't Touch the Slow Parts V2
Federico Galassi
 
Please Don't Touch the Slow Parts
Federico Galassi
 
Javascript The Good Parts v2
Federico Galassi
 
Javascript The Good Parts
Federico Galassi
 

Recently uploaded (20)

PDF
Trying to figure out MCP by actually building an app from scratch with open s...
Julien SIMON
 
PDF
This slide provides an overview Technology
mineshkharadi333
 
PDF
Software Development Company | KodekX
KodekX
 
PPTX
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
PDF
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
PDF
Brief History of Internet - Early Days of Internet
sutharharshit158
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PDF
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
PDF
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
PDF
Software Development Methodologies in 2025
KodekX
 
PDF
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
PPT
Coupa-Kickoff-Meeting-Template presentai
annapureddyn
 
PDF
Doc9.....................................
SofiaCollazos
 
PDF
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
PDF
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
PPTX
How to Build a Scalable Micro-Investing Platform in 2025 - A Founder’s Guide ...
Third Rock Techkno
 
PPTX
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
PDF
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
Trying to figure out MCP by actually building an app from scratch with open s...
Julien SIMON
 
This slide provides an overview Technology
mineshkharadi333
 
Software Development Company | KodekX
KodekX
 
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
Brief History of Internet - Early Days of Internet
sutharharshit158
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
Software Development Methodologies in 2025
KodekX
 
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
Coupa-Kickoff-Meeting-Template presentai
annapureddyn
 
Doc9.....................................
SofiaCollazos
 
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
How to Build a Scalable Micro-Investing Platform in 2025 - A Founder’s Guide ...
Third Rock Techkno
 
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 

Event Driven Javascript