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

Javascript Events #DevCamp7

Javascript Events #DevCamp7

Florian Strzelecki

April 10, 2013
Tweet

More Decks by Florian Strzelecki

Other Decks in Programming

Transcript

  1. 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
  2. Event handler var handler = function (event) { alert('You clicked

    me!'); } ; document.addEventListener('click', handler);
  3. Event handlers var handler = function (event) { alert('You clicked

    me!'); } ; document.addEventListener('click', handler); document.addEventListener('click', function (event) { alert('Another event handling...'); } );
  4. Real Life Application <form action="#" onsubmit="confirm(this);"> ... </form> <script> function

    confirm(form) { if(condition()) { form.submit(); } } </script>
  5. 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
  6. 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);
  7. Custom event handler // where you want in your code

    document.addEventListener('build', function (event) { alert('Build complete'); } );
  8. 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 »
  9. 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 ».
  10. Example : User Plugin • User events : – user_connected

    – user_disconnected – user_some_action – user_updated
  11. 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.