Jun 25

I am a big fan of both Andrew Dupont, and custom events.

In his presentation he goes through some very nice use cases. Some are cross cutting (e.g. the fact that you can unit test, or debug, or … so much easier) and some are specific such as:

Scripty2 animation heartbeat

JAVASCRIPT:

// keep the heartbeat going
setTimeout(function() {
  document.fire(“effect:heartbeat”);
}, 0);

// listen in
document.observe(“effect:heartbeat”, advanceEffectByOneFrame);

// allows for nice debugging
document.observe(“keydown”, function(event) {
  if (event.keyCode === Event.KEY_RIGHT) {
    document.fire(“effect:heartbeat”);
  }
});
 

Another nice example is how you can start using the new and cool EventSource while retrofitting the functionality for browsers who don’t implement the new standard:

JAVASCRIPT:

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

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

// observer works for both
$(document).observe(‘data:received’, function(event) {
  doStuff(event.memo);
});
 

And, there are many more great examples in the slides.

How have you been using custom events?

[Ajaxian ยป Front Page]

This website uses IntenseDebate comments, but they are not currently loaded because either your browser doesn't support JavaScript, or they didn't load fast enough.

Leave a Reply

preload preload preload