Delivered at TXJS (http://texasjavascript.com) on June 5, 2010.
All the major frameworks support custom events. All framework authors love custom events and want you to use them. But few people actually do.
Custom events aren’t a gimmick. The ability to fire your own events — just like the browser fires click, mousemove, focus, and all the rest — can solve many of the problems large JS projects face.
We’ll look at a handful of recipes for integrating custom events into your own code. You’ll learn how to fire custom events in each of the major JavaScript frameworks, and explore the advantages that custom events have over a standard callback pattern.
33. Step through an animation
frame by frame
document.observe('keydown', function(event) {
if (event.keyCode === Event.KEY_RIGHT) {
document.fire('effect:heartbeat');
}
});
53. 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();
}
60. (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);
})();
61. Then you’d be able to do
something like this:
document.observe('key:left', function() { moveSlide(-1); });
document.observe('key:right', function() { moveSlide( 1); });
65. 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);
});
66. for browsers that don’t
new Ajax.Request('/legacy/polling', {
onComplete: function(request) {
document.fire('data:received', request.responseJSON);
}
});
67. observer works with either approach
$(document).observe('data:received', function(event) {
doStuffWithYourData(event.memo);
});
68. …and your unit tests can fire dummy data
function testThatSomethingHappened() {
document.fire('data:received', FIXTURE_DATA);
assertSomething();
}