While working on a very large ajax-y application, I found myself facing the following scenario:

1. Tons of custom (non-DOM) events.
2. These events are firing from very deeply-nested classes.
3. I wanted these events to communicate with “long-range” instances, far outside the currently executing scope block.
4. I wanted to preserve the scope of callbacks.

In english, I had a few “top-level” class instances – e.g., Records, Users, Forms, Search, Layout – usually one instance each in the highest common scope (the scope of the domready callback). In each of these were tons of specialized class instances, like in Records I had a RecordsView, in that a RecordsControls, in that a RecordsPager, etc – and the only reference to a RecordsPager instance existed in the RecordsControls instance, etc – and I wanted to execute a callback on an instance similarly nested. Since these weren’t DOM elements, we don’t get bubbling. To emulate bubbling, you end up with a bunch of listeners just grabbing the same event and passing it back up to the next highest scope.

To start, I was able to manage pretty well with member instances, and had a lot of this lying around (in constructors):

But there were quite a few places where the same event was firing, but from very different sources and in very distant scopes. For example, whenever a ‘ViewRecord’ event happened – regardless of where it happened – I needed to show some information about the record – and this event might fire from any number of sources, some of which might pass data that other sources might not. Further, the callbacks needed to stay within scope, so if a ControlButton instance should fire Recordset.View on click, it should still fire from Recordset’s scope.

So I came up with a quick little class that I instance once at the top level, prior to instancing anything else, and use it as a bridge:

Usage might look like this:

This would pass the event *intact* to the callback, including the event object in the case of a DOM event.

Nothing fancy, but might be handy in a larger application with many levels of nested scope.