how custom events will save the universe

80
How CUSTOM EVENTS will save the universe

Upload: andrew-dupont

Post on 10-Jul-2015

14.583 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: How Custom Events Will Save the Universe

How CUSTOM EVENTS

will save the universe

Page 2: How Custom Events Will Save the Universe

Law of Demeter

Page 3: How Custom Events Will Save the Universe

“Each unit should have only limited knowledge

about other units.”

Page 4: How Custom Events Will Save the Universe

(we break this ruleall the time)

Page 5: How Custom Events Will Save the Universe

the Law of Demeter is about removing

unnecessary coupling

Page 6: How Custom Events Will Save the Universe

custom events can helpdecouple your code

Page 7: How Custom Events Will Save the Universe

Broadcaster and receiverdon’t have to knowabout one another…

Page 8: How Custom Events Will Save the Universe

… so there’s far less to mockin your unit tests

Page 9: How Custom Events Will Save the Universe

YOU DO HAVEUNIT TESTS, RIGHT?

Page 10: How Custom Events Will Save the Universe

How do custom events work?

Page 11: How Custom Events Will Save the Universe
Page 12: How Custom Events Will Save the Universe

$(document).observe('custom:event', function(event) { var customData = event.memo; // stuff}); $('troz').fire('custom:event', { foo: "bar" });

Page 13: How Custom Events Will Save the Universe
Page 14: How Custom Events Will Save the Universe

$(document).bind('customevent', function(event, customData) { // stuff}); $('#troz').trigger('customevent', [{ foo: "bar" }]);

Page 15: How Custom Events Will Save the Universe
Page 16: How Custom Events Will Save the Universe

$(document).addEvent('customevent', function(event, customData) { // stuff}); $('troz').fireEvent('customevent', { foo: "bar" });

Page 17: How Custom Events Will Save the Universe

BUT WHY?

Page 18: How Custom Events Will Save the Universe

Makes testing easier

(maybe you’ll do it now)

Why?

Page 19: How Custom Events Will Save the Universe

Rapid prototyping

Why?

Page 20: How Custom Events Will Save the Universe

More versatile than callbacks

Why?

Page 21: How Custom Events Will Save the Universe

Can be bubbled/canceled

Why?

Page 22: How Custom Events Will Save the Universe

Can handle exceptions properly(in theory)

Why?

Page 23: How Custom Events Will Save the Universe

(quoth Dean Edwards)

Page 24: How Custom Events Will Save the Universe

In Prototype,exceptions raised in one handler

won’t affect another handler

Page 25: How Custom Events Will Save the Universe

(is this a big deal? smart people disagree)

Page 26: How Custom Events Will Save the Universe

CASESTUDIES

Page 27: How Custom Events Will Save the Universe

#1

Case Studies

Page 28: How Custom Events Will Save the Universe

(script.aculo.us 2.0)

Case Studies

Page 29: How Custom Events Will Save the Universe

…as a “metronome” for effects

scripty2 uses custom events…

Page 30: How Custom Events Will Save the Universe

window.setTimeout(function() { document.fire('effect:heartbeat');}, 0);

Page 31: How Custom Events Will Save the Universe

document.observe('effect:heartbeat', advanceEffectByOneFrame);

Page 32: How Custom Events Will Save the Universe

Seems pointless…

…until you need to debug

Page 33: How Custom Events Will Save the Universe

Step through an animationframe by frame

document.observe('keydown', function(event) { if (event.keyCode === Event.KEY_RIGHT) { document.fire('effect:heartbeat'); }});

Page 34: How Custom Events Will Save the Universe

…to pass messagesbetween UI widgets

scripty2 uses custom events…

Page 35: How Custom Events Will Save the Universe
Page 36: How Custom Events Will Save the Universe
Page 37: How Custom Events Will Save the Universe

S2.UI.Menu

(used by other S2.UI components)

Page 38: How Custom Events Will Save the Universe

var menu = new S2.UI.Menu();menu.addChoice("Foo");menu.addChoice("Bar");someElement.insert(menu);menu.open();

Page 39: How Custom Events Will Save the Universe

menu.observe('ui:menu:selected', function(event) { console.log('user clicked on:', event.memo.element);});

S2.UI widgets act like elements when needed, so...

Page 40: How Custom Events Will Save the Universe

Easy to usein any context

Page 41: How Custom Events Will Save the Universe

Button with menu

Page 42: How Custom Events Will Save the Universe

ASIDE:

Custom events are cancelable

Page 43: How Custom Events Will Save the Universe

var event = $('troz').fire('custom:event');if (!event.stopped) performSomeDefaultAction();

Page 44: How Custom Events Will Save the Universe

document.observe('ui:menu:before:open', function(event) { event.stop();});

(prevent all menus from appearing)

Page 45: How Custom Events Will Save the Universe

…as hooks for debugging

scripty2 uses custom events…

Page 46: How Custom Events Will Save the Universe

“Why aren’t theseeffects queueing

like I expect?”

Page 47: How Custom Events Will Save the Universe

document.observe('effect:dequeued', function(event) { var queue = event.memo; console.log("Effects in queue:", queue.size());});

Page 48: How Custom Events Will Save the Universe

You get debuggingFOR FREE

Page 49: How Custom Events Will Save the Universe

#2

Case Studies

Page 50: How Custom Events Will Save the Universe

Mouse wheel

Case Studies

Page 51: How Custom Events Will Save the Universe

window.addEventListener('DOMMouseScroll', handler);window.onmousewheel = handler;

function handler(event) { var delta; if (event.wheelDelta) { delta = event.wheelDelta / 120; if (window.opera) delta = -delta; // (not a joke) } else if (event.detail) { delta = -event.detail / 3; }

// Do stuff with your stupid delta}

http://adomas.org/javascript-mouse-wheel/

Page 52: How Custom Events Will Save the Universe

Instead, do this:

Page 53: How Custom Events Will Save the Universe

window.addEventListener('DOMMouseScroll', handler);window.onmousewheel = handler;

function handler(event) { var delta; if (event.wheelDelta) { delta = event.wheelDelta / 120; if (window.opera) delta = -delta; // (not a joke) } else if (event.detail) { delta = -event.detail / 3; }

// Fire a custom event with the normalized delta. var result = event.target.fire('mouse:wheel', { delta: delta }); if (result.stopped) event.preventDefault();}

Page 54: How Custom Events Will Save the Universe

See also:

hashchange

Page 55: How Custom Events Will Save the Universe

#3

Case Studies

Page 56: How Custom Events Will Save the Universe

User idle state

Case Studies

Page 57: How Custom Events Will Save the Universe

credit: kangax

document.observe('state:idle', function() { turnOffBackgroundAjaxRequests();});

document.observe('state:active', function() { turnOnBackgroundAjaxRequests();});

http://perfectionkills.com/detect-idle-state-with-custom-events/

Page 58: How Custom Events Will Save the Universe

#4

Case Studies

Page 59: How Custom Events Will Save the Universe

Keyboard events

Case Studies

Page 60: How Custom Events Will Save the Universe

(function() { var KEYS = {}; KEYS[Event.KEY_ESC] = "esc"; KEYS[Event.KEY_UP] = "up"; KEYS[Event.KEY_DOWN] = "down"; KEYS[Event.KEY_LEFT] = "left"; KEYS[Event.KEY_RIGHT] = "right"; // ... and so on

function handler(event) { if (event.keyCode && KEYS[event.keyCode]) { event.element().fire("key:" + KEYS[event.keyCode], event); } }

document.observe("keydown", handler);})();

Page 61: How Custom Events Will Save the Universe

Then you’d be able to dosomething like this:

document.observe('key:left', function() { moveSlide(-1); });document.observe('key:right', function() { moveSlide( 1); });

Page 62: How Custom Events Will Save the Universe

#5

Case Studies

Page 63: How Custom Events Will Save the Universe

Data broadcasting

Page 64: How Custom Events Will Save the Universe

Server-sent events are awesome……but not universally supported

Page 65: How Custom Events Will Save the Universe

for browsers that support server-sent events

var eventSource = $('event_source');eventSource.observe('server-sent-event-name', function(event) { document.fire('data:received', event.data);});

Page 66: How Custom Events Will Save the Universe

for browsers that don’t

new Ajax.Request('/legacy/polling', { onComplete: function(request) { document.fire('data:received', request.responseJSON); }});

Page 67: How Custom Events Will Save the Universe

observer works with either approach

$(document).observe('data:received', function(event) { doStuffWithYourData(event.memo);});

Page 68: How Custom Events Will Save the Universe

…and your unit tests can fire dummy data

function testThatSomethingHappened() { document.fire('data:received', FIXTURE_DATA); assertSomething();}

Page 69: How Custom Events Will Save the Universe

FAQ

Page 70: How Custom Events Will Save the Universe

“What if my eventsaren’t DOM-related?”

FAQ

Page 71: How Custom Events Will Save the Universe

(meh)

Page 72: How Custom Events Will Save the Universe

Use the DOM anyway, I say

Page 73: How Custom Events Will Save the Universe

“Isn’t this overkill?”

FAQ

Page 74: How Custom Events Will Save the Universe

Yes, sometimes

Page 75: How Custom Events Will Save the Universe

“Aren’t events slow?”

FAQ

Page 76: How Custom Events Will Save the Universe

NO

Page 77: How Custom Events Will Save the Universe

Events aren’t slow;they’re synchronous

Page 78: How Custom Events Will Save the Universe

Events are onlyas slow as the handlers

attached to them

Page 79: How Custom Events Will Save the Universe

If performance is a concern, defer

window.setTimeout(function() { document.fire('costly:custom:event');}, 0);

Page 80: How Custom Events Will Save the Universe

QUESTIONS?

Andrew Dupont

http://andrewdupont.net