Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Javascript Events #DevCamp7

Javascript Events #DevCamp7

1e88e032d61a9343dca0a7fc9cccc7b4?s=128

Florian Strzelecki

April 10, 2013
Tweet

Transcript

  1. <user ontalk="devamp.talk('JS Event')" id="@Exirel" />

  2. Events « Many objects can have event handlers specified. These

    act as non-capture event listeners for the object on which they are specified. » - HTML Spec
  3. Event handler var handler = function (event) { alert('You clicked

    me!'); } ; document.addEventListener('click', handler);
  4. (merci http://jsfiddle.net/)

  5. Event handlers var handler = function (event) { alert('You clicked

    me!'); } ; document.addEventListener('click', handler); document.addEventListener('click', function (event) { alert('Another event handling...'); } );
  6. div p span Capturing Bubbling Capturing vs Bubbling

  7. Real Life Application <form action="#" onsubmit="confirm(this);"> ... </form> <script> function

    confirm(form) { if(condition()) { form.submit(); } } </script>
  8. DreamWeaver FrontPage « WYSIWYG DHTML » IT'S A CRAP!

  9. Event nightmares • Who is « this »? • Cross-browser

    features (requires framework) • element.attachEvent (IE 6-8) • capturing vs. bubbling (IE only use bubbling) ➔ A framework is a good solution
  10. Custom Event // create the event var evt = document.createEvent('Event');

    // define that the event name is `build` evt.initEvent('build', true, true); // elem is any element (including document) elem.dispatchEvent(evt);
  11. Custom Event (new) var evt = new CustomEvent('build'); // fire

    the event. elem.dispatchEvent(evt);
  12. Custom event handler // where you want in your code

    document.addEventListener('build', function (event) { alert('Build complete'); } );
  13. Loose coupling « A loosely coupled system is one in

    which each of its components has, or makes use of, little or no knowledge of the definitions of other separate components. » - Wikipedia « Loose coupling »
  14. Loose coupling • Fire event on `document` when your application

    want to say « something happens » • Add handler on `document` when you need it. Into a plugin. Or another one. Or into your main script, or... ➔ Event on `document` your « application level events ».
  15. Loose coupling Events in your application are like your API.

  16. Example : User Plugin • User events : – user_connected

    – user_disconnected – user_some_action – user_updated
  17. Example : User Plugin • Application Handler : – Handler

    on « user_connected » to load the User profile – Handler on « user_disconnected » to display the login form • Another plugin : – Handler on « user_some_action » to trigger another action, event, etc.
  18. document.addHandler('devcamp_talk_end', function (event) { alert('Thanks!'); } );