Slide 1

Slide 1 text

Slide 2

Slide 2 text

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

Slide 3

Slide 3 text

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

Slide 4

Slide 4 text

(merci http://jsfiddle.net/)

Slide 5

Slide 5 text

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

Slide 6

Slide 6 text

div p span Capturing Bubbling Capturing vs Bubbling

Slide 7

Slide 7 text

Real Life Application ... function confirm(form) { if(condition()) { form.submit(); } }

Slide 8

Slide 8 text

DreamWeaver FrontPage « WYSIWYG DHTML » IT'S A CRAP!

Slide 9

Slide 9 text

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

Slide 10

Slide 10 text

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);

Slide 11

Slide 11 text

Custom Event (new) var evt = new CustomEvent('build'); // fire the event. elem.dispatchEvent(evt);

Slide 12

Slide 12 text

Custom event handler // where you want in your code document.addEventListener('build', function (event) { alert('Build complete'); } );

Slide 13

Slide 13 text

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 »

Slide 14

Slide 14 text

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 ».

Slide 15

Slide 15 text

Loose coupling Events in your application are like your API.

Slide 16

Slide 16 text

Example : User Plugin ● User events : – user_connected – user_disconnected – user_some_action – user_updated

Slide 17

Slide 17 text

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.

Slide 18

Slide 18 text

document.addHandler('devcamp_talk_end', function (event) { alert('Thanks!'); } );