Update, 7/1/2009: Switched code sections from manual coloring to an automatic syntax formatting plugin.
NOTE (6/20/2009): I didn’t intend to close comments on this post. The setting is on “enabled” and I’ve tried disabling and re-enabling them to no avail. Some glitch either with the WordPress 2.8 update or installing the new theme has screwed it up. If you have something to say about this post, drop me a line. My Gmail username is the same as everywhere else.
I haven’t been posting much lately; I have, however, been thinking about my future in some area of computer science, software development, and/or web development. And I’ve been tinkering more with JavaScript since my last post. One thing I’ve discovered how to do is baking event handling into your custom objects. This isn’t really innovative—all the major frameworks out there include it—but I had fun figuring it out on my own. Here’s the solution I arrived at.
I decided that the best way to store and fire event listeners was in an associative array, where the keys are the event names and the values are associative arrays linking IDs to functions. So, for example, a set of registered event listeners for an object representing a door might look like this:
Door.Event
"Open" => "a" => function
"Close" => "b1" => function
"c" => function
"Lock" => (empty)
"Unlock" => "b2" => function
"d" => function
The IDs here are just quick meaningless samples; the idea is that they come from and uniquely identify the object that registered their respective event listeners. They will be used by their originating object to unregister its own event listeners and not any other object’s event listeners if need be, since you may have multiple objects registering listeners for the same event, possibly even the same function registered as a listener by multiple objects. As an example of this, consider a card game. If there are two cards on the board that say, “Whenever a player discards a card, that player takes 5 damage,” you will have two instances of the triggered function (dealing 5 damage to the player) registered on an array of global events for “Discard”, and when that event is fired, both will go off and the function will be executed twice. Yet, if one of those cards is destroyed, it should remove its own specific instance of event listener registration—perhaps the other has had a spell cast on it modifying its effect, so it could matter which one gets deregistered.
Using this system, implementing event listener registration is simple.
