Event driven javascript

  • 1,940 views
Uploaded on

Why is web application programming so difficult? Is it javascript fault? Is it our fault? Time to take the red pill and wake up in the real, event driven world. A world where if you can dodge the …

Why is web application programming so difficult? Is it javascript fault? Is it our fault? Time to take the red pill and wake up in the real, event driven world. A world where if you can dodge the bullets of skyrocketing complexity, your programs can be made scalable, fault tolerant, extensible and just beautiful.

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
1,940
On Slideshare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
6
Comments
0
Likes
1

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. Event Driven Javascriptfederico.galassi@cleancode.itslidehare.net/fgalassi
  • 2. • Event driven programming• History of javascript design• Event driven javascript
  • 3. Softwarecomponents exchangeinformation
  • 4. Producers giveinformation
  • 5. Consumers takeinformation
  • 6. Taxonomy ofinteraction models
  • 7. Who is theproducer ?
  • 8. KnownWhere’s Kenny? Over There!
  • 9. UnknownWhere’s Kenny? Over There! Where’s Kenny?
  • 10. Who is theproducer ?known unknown
  • 11. How doesinformation flow ?
  • 12. PullWhere’s Kenny? Over There!
  • 13. Push Let me know where’s Kenny Ok... later ...Hey! Over There!
  • 14. How does information flow ? known unknownpullpush
  • 15. 4 Models ofinteraction
  • 16. 1. known unknown Requestpull Responsepush
  • 17. Request Response//  method  invocationweapon  =  armory.buy(“shuriken”)kenny  =  cartman.findKenny()kenny.kill(weapon)
  • 18. RequestResponse SIMPLE
  • 19. RequestResponse SIMPLE SEQUENTIAL
  • 20. RequestResponse SIMPLE SEQUENTIAL IMPERATIVE
  • 21. RequestResponseHUMAN
  • 22. Request Response TIGHTCOUPLING SEQUENTIAL IMPERATIVE
  • 23. Request Response TIGHTCOUPLINGINEFFICIENT SEQUENTIAL IMPERATIVE
  • 24. 2. known unknown Anonymous Requestpull Request Response Responsepush
  • 25. AnonymousRequest Response The system decouplesinformation and its owner
  • 26. AnonymousRequest Response load balancer
  • 27. Anonymous Request Responsealancer FAILOVER
  • 28. Anonymous Request Responsealancer FAILOVER EXTENSIBLE
  • 29. Anonymous Request Response SYSTEMCOMPLEXITY
  • 30. 3. known unknown Anonymous Requestpull Request Response Responsepush Callback
  • 31. Callback//  observer  patterncartman.findKenny(    function(kenny)  {        kenny.kill(weapon)})
  • 32. Don’t call usWe’ll call you
  • 33. From Sequential COMPUTATIONINPUT OUTPUT STATE
  • 34. To State MachineINPUT STATE A COMPUTATIONINPUT STATE B COMPUTATIONINPUT STATE C OUTPUT
  • 35. CallbackRelinquish control
  • 36. Callback Just in time is optimal ProducersConsumer
  • 37. Callback efficiency
  • 38. CallbackEXPLICIT efficiencyCONTROL FLOW
  • 39. 4. known unknown Anonymous Requestpull Request Response Responsepush Callback Event Driven
  • 40. Callback + AnonymousRequest Response = EVENTS
  • 41. Home Automation Example
  • 42. EVENTS FAILOVER + system COMPLEXITY +EXTENSIBLE + explicit efficiency = control flow =------------------------- ------------ ------------- ------------ ------------ power chaos
  • 43. Expressive Power EVENTS ANON.CALLBACK REQUEST REQUEST RESPONSE RESPONSE
  • 44. Complexity
  • 45. Javascript isevent driven
  • 46. NotJavascript Fault
  • 47. NotYourFault
  • 48. Just anHARDERproblem
  • 49. • Event driven programming• History of javascript design• Event driven javascript
  • 50. In the old days... Netscape Headquarters May 1995
  • 51. This guy had two problems... Brendan Eich Creator of Javascript
  • 52. 1. The world is Concurrent
  • 53. ... and so is browser
  • 54. User InputNetwork Requests
  • 55. 2. Very very very short timeLiveScript first shipped in betas of Netscape Navigator 2.0 in September 1995
  • 56. BePragmatic
  • 57. He could useThreads ... Real preemptive concurrency
  • 58. Threads are Evil
  • 59. He could useCoroutines ... Emulated cooperative concurrency
  • 60. needs acomplex scheduler
  • 61. He was afunctional guy
  • 62. Take it easyNot concurrentJust non-blocking
  • 63. First class functions//  callbacks  give//  non  linear  executionwally.takeJob(function  work()  ...)wally.getCoffee(function  drink()  ...)//  ...  later  ...//  first  drink  coffee//  then  work
  • 64. Simple event loop //  make  it  look  concurrent button.onclick(function()  { div.style.color  =  “red” }) UI UI update Click handlerevent UI update Click handlerqueue Click handlertime User click
  • 65. Non-blocking I/O//  network  async  apixhr.onreadystatechange  =  function(){ ...})//  DOM  in  memorydiv.innerHTML  =  “Hello”
  • 66. Javascript won
  • 67. But sold its soulfor simplicity
  • 68. One thread = Freeze
  • 69. No Wait()
  • 70. Simple sequentialfunction  breakfast()  { var  bacon  =  bacon() var  juice  =  orangeJuice() eat(bacon,  juice)} computationfunction  bacon()  { //  get  bacon return  bacon}
  • 71. Async gets infunction  breakfast()  { var  bacon  =  bacon() wrong var  juice  =  orangeJuice() eat(bacon,  juice)}function  bacon()  { getBacon(function(bacon)  { //  got  bacon }) return what?}
  • 72. Break computationfunction  breakfast()  {      var  callback  =  function(bacon)  { var  juice  =  getOrangeJuice() eat(bacon,  juice) } rest of computation bacon(callback)} computationfunction  bacon(callback)  { //  get  bacon  async callback(bacon)}
  • 73. Break morefunction  breakfast()  {      var  callback  =  function(bacon)  { var  callback  =  function(juice)  { eat(bacon,  juice) rest of computation 2 } getOrangeJuice(callback) } rest of computation 1 bacon(callback)} computation
  • 74. Continuation Passing Style
  • 75. it’s Viral 1//  simple  sequential  computationfunction  A()  {  return  B()  }function  B()  {  return  C()  }function  C()  {  return  value  }A()
  • 76. it’s Viral 2//  C  becomes  async,  everything  becomes  asyncfunction  A(callback)  { B(function(value)  {  callback(value)  })}function  B(callback)  { C(function(value)  {  callback(value)  })}function  C(callback)  {  callback(value)  }A()
  • 77. it’s Hard sleep//  simple  sequential  sleepsleep(3000)doSomething()
  • 78. it’s Hard sleep//  not  so  simple  sleepsetTimeout(function()  { doSomething()},  3000)
  • 79. it’s Hard loop//  simple  sequential  loopimages.forEach(function(url) var  image  =  fetchImage(url) image.show()}
  • 80. it’s Hard loop//  fetchImage  is  asyncimages.forEach(function(url) fetchImage(url,  function(image)  { image.show() })}
  • 81. it’s Hard loop//  Show  them  in  the  right  orderfunction  processImage()  { var  url  =  images.shift() if  (url)  { fetchImage(url,  function(image)  { image.show() processImage() }) }}processImage()
  • 82. Javascript sacrificedconveniencefor simplicity
  • 83. ... and it was the right choice
  • 84. • Event driven programming• History of javascript design• Event driven javascript
  • 85. How can we tamecomplexity?
  • 86. AddWait()stupid!
  • 87. Easy sleep//  simple  sequential  sleep  with  wait/resumesleep(3000)doSomething()function  sleep(msec)  { wait( setTimeout(function()  { resume() },  msec) )}
  • 88. Beautiful
  • 89. Already done !
  • 90. //  write  sequential  logicfunction  doOpsABC()  { waitfor  { var  x  =  doOpA() } and  { var  y  =  doOpB() } return  doOpC(x,y)} http://stratifiedjs.org/
  • 91. Transform tocontinuation passing style
  • 92. //  synchronous  readfs.read(path).wait() http://nodejs.org/
  • 93. Implementcoroutines
  • 94. Back tocomplexity
  • 95. Jeremy Ashkenas - CoffeeScript “Case in point, Stratified JS: A virtuoso performance of JavaScript compilation, but look at what it compiles into.” “I dont think we want to take CoffeeScript down that path. Open the Pandoras box of injecting special functions into the runtime, and ... suddenly you have to worry about being orders of magnitude slower than normal JS.” https://github.com/jashkenas/coffee-script/issuesearch?state=closed&q=asynchronous#issue/350/comment/330116
  • 96. Jeremy Ashkenas - CoffeeScriptvar getDocument = function(){ var getDocument; waitfor(document) { __oni_rt.exec(__oni_rt.Seq(0,__oni_rt.Seq(0,__oni_rt.Nblock( resume(db.get(id)); function(arguments){ } getDocument=function (){ return document; 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);
  • 97. Ryan Dahl - node.js “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 Im trying to avoid in Node.” http://groups.google.com/group/nodejs/msg/df199d233ff17efa
  • 98. Take it easy No wait()Just flow control
  • 99. Sequence 1//  async  sequential  computationsequence(get,  filter,  process)function  get(resume)  { $.get(url,  function(data)  { resume(data) })}function  filter(resume,  data)  {  ...  }function  process(resume,  data)  {  ...  }
  • 100. Sequence 2//  async  sequential  computationfunction  sequence()  { var  steps  =  arguments.slice() var  doStep  =  function(val)  { var  next  =  steps.shift() if  (next)  { next.apply(null,  [doStep,  val]) } } doStep()}
  • 101. Functional programmingfirst(fetchA,  fetchB,  fetchC)every(checkA,  checkB,  checkC)map(array,  mapper)filter(array,  filter)
  • 102. From imperativevar  clicks  =  0,  timeout  =  null$(“button”).click(function()  { clicks++ if  (clicks  ==  1)  { timeout  =  setTimeout(function()  { clicks  ==  0 }) } if  (clicks  ==  3)  { clearTimeout(timeout) clicks  =  0 $(this).trigger(“tripleclick”) }})
  • 103. To declarative$(button) .on(“click”) .times(3) .within(“1  second”) .trigger(“tripleclick”)
  • 104. Questions?
  • 105. federico.galassi@cleancode.it