A stab at application event dispatch
Javascript in browsers, and more specifically the DOM, provide near-limitless means to build interactive and dynamic client-side software systems. People are scripting the DOM, invoking other services like XMLHTTPRequest, and making lots of pretty coolness happen on their web sites these days.
But there's a bit of a problem. We don't have any standard way to deal with event dispatch within the innards of an application.
Why should I care?
Because you can connect blobs of intelligent behaviour together with a reasonable event dispatch system, so that it's easier to factor out these behaviors into reusable components.
How to do it with as little cruft as possible:
We should isolate the idea of event dispatch from everything else about how events are used. That way, the system is as general as possible, without being too general.
A single event queue for a single type of event from a single source object is probably the simplest, most atomic unit of glue for this project. Here's some javascripty pseudo code:
function Q() {
this.q = []
this.lock = false
}
Q.prototype = {
add: function(fn) {
if (fn not in this.q) this.q.push(fn)
},
del: function(fn) {
# remove fn from this.q, if it's there.
},
dispatch: function(evt) {
if (this.lock) complain about an event broadcast cycle, else:
this.lock = true
for (k in this.q) this.q[k](evt)
this.lock = false
}
}We can then write:foo.onbar = new Q()and later on:
foo.onquux = new Q()
foo.onquux.add(function() {alert('QUUX ALERT!')})and eventually:foo.onquux.dispatch()
I'm solving two problems in advance here.
First, many uses of event queues wish to send notification data along the path, so it's possible to include an argument to further describe the details, such as a pixel coordinate or whatever.
Second, it's almost certainly a bug if, while processing one event, another is dispatched along the same channel. Most times, this means that you've got an infinite loop. Other times, it might mean a logical flaw. In any case, the toolmaker doesn't know what to do here. The detection method is crude, but it should work in the single-threaded VM that browsers seem to have.
A fleshed out version of this code would help to separate concerns in development. One component can process the business logic, and rely on event dispatch to let a presentation layer control the various parts of the browser. Indeed, components written with this model can be stacked to any degree without too much programmer brainpower, which is the real point of such a system.
The main drawback is that this isn't completely consistent with DOM methods for adding event listeners to the base UI widgets. However, I don't think that's important. DOM nodes are only exposed to a small portion of the code in the presentation layer, and if you need the generality, you can write a wrapper class.

0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home