Publishing Custom Events in JavaScript
By now anyone who spent at least one week of learning JavaScript in their life, they know about events. Although they may not exactly know all of them or how to make them do something upon them firing, we should all indeed know of the select few like click, dblclick, mouseover, mouseout, focus, blur, and submit to name a couple. These are all events known to us that we can define as interesting moments
available to us in the DOM that we can listen for. Got it? Wonderful...
So what's a custom event?
A custom event(s) is/(are) the interesting moments
that you get to define in your web application. Still confused? Yea. I think I was too. If this is a new concept to you, don't feel left out. Keep in mind this isn't a built-in JavaScript function, but rather a proof of concept that allows for better event abstraction.
Brief overview of normal DOM events
When we describe normal events to our peers as a series of interactions, we generally say something like For this tab menu, I want to swap the colors, then change the message on 'click' of the tab.
. Or if that sounds too awkward. We'll say When the user 'clicks' on the tab, I want to swap the colors and change the message.
I can see it swindling in your brain already. Sure enough, the first thing that would normally come to a scripters mind is.... I'll assign a 'click' event to the tab that fires a function which will swap the colors, then change the message
. Fair enough. That totally works and that's the way most people do it. As a matter of fact, just about all the code on this site follows that model as well... nevermind the fact that it's about a year old now since I last touched it.
Examples of custom events
A custom event in this same model can be something you, yes you, get to make up. Looking at our tab/click/swapColor/changeMessage illustration, we can easily turn this into an event called onTabChange. In return, anytime our tab menu changes state, we can notify our listeners/subscribers that this event occured; then do whatever the heck we want on the fly.
A Parallel illustration
Think about the normal event model. There are event handlers, and there are event listeners. The benefits of a listener (IMO) far outweigh those of a handler. Mainly because a handler is something that 'handles' that event when triggered, and a listener can be one of many that just sits around and waits for the event to fire. If that doesn't make any sense. Just know that there can only be one event handler, but several listeners. A handler is more likely to get overridden.
Likewise, custom event subscribers follow the same model as listeners. Take special note that just a 'custom event' all by itself is not does not need to follow the subscriber/listener model; that in and of itself is just the thing you get to define. It can be a handler or a listener event.So, how do I make a custom event?
First of all, you need to decide which parts of your web site are going to have these custom events, and if they're going to be useful to publish. Although you may be the only consumer of these events (meaning, nobody else is working on the project but you), it's still probably a good idea to abstract your events.
Whoa. Hold up. Can I get some more examples?
Sure. Here's a random compiled list that could possibly qualify as custom events:
- onMenuCollapse
- onMenuOpen
- onColorChange
- onDrag (drag and drop)
- onDragComplete
- onTween (animation)
- onColorPick
- onSlide
- onUserWaitedTooLong
- onRotate (tetris)
- onMoveLeft (tetris)
- onMailCompose
- onHilight
- onEdit
- onSave
- onUpdating
- onComplete
So how do I make these happen?
Glad you asked. After you've decided what would be useful to have as a custom event, you can use the YUI event utility to define your events, subscribe to them, then fire them at will (what? You weren't expecting me to talk about Yahoo! again?).
First off, the code is dirt simple. Assuming you've planted the correct files into your web document like follows:
adding YUI event util
<head>
...
<script type='text/javascript' src='js/yahoo.js'></script>
<script type='text/javascript' src='js/event.js'></script>
...
</head>
From this point on, it's best to assume the following two rules for making custom events.
Rule 1) As the Producer/Publisher of the events, we decide what qualifies as the event and define it. Furthermore we are also the ones that get to fire the event.
Rule 2) As the Consumer of these events, we get to subscribe and fire whatever functions we want when those events get fired from our publisher.
So, as the publisher we can now define our custom event:
defining your custom event
var onMenuCollapse = new YAHOO.util.CustomEvent('menu collapse');
And now fire it at some point in our library.
firing your custom event
/* paZow Sucka */
onMenuCollapse.fire();
In a real-world situation, if you're part of a team of developers, it would be best to notify the fact that you've published this event. Thus noting to the others that they can listen for this event at whatever moment they want if they need to update the document at a later time. If these developers aren't around.... then document the hell out of your code noting that You can listen for this event!However, that's unlikely. Most folks coming in at a later time aren't going to know what a custom event is.... so they can call you and you can act like the chosen smart one ;)
Subscribing to the custom event
Simple enough. You can listen for it like this:subscribing to an event
onMenuCollapse.subscribe(swapColors);
.
.
.
function swapColors() {
// do stuff here
}
Wonderful, can I see something?
Sure. Like most practical developers, you often need to see something. One pet peeve of mine is reading JavaScript tutorials that just talk about the language itself and philosophies of code rather than showing a real use of it all. It would be the equivalent of trying to explain OO JavaScript while talking about bears, balloons, boats, and other forms of animals and fairies.
Anyway, here is the most basic (dull) example for you to get an idea of how custom events work with a simple event called 'myEvent'. You can view that here. You might even come back to that example because it shows you what you can do with certain perameters and arguments etc...
Here is an illustration of Drag and Drop custom events being extended to have subscribers
(which it normally doesn't have (FYI - feature request)). You'll notice that the instance of the box being dragged has an onDragging event and an onComplete event that you can subscribe to. Take special note that the onComplete event is being fired twice to change the colors of each of the boxes.
Of course, here is another example of an Animation Menu with Custom Events which illustrates the use of onMenuOpen and onMenuCollapse.
In all cases I advise you to take a peek at the code to get a better understanding of what's actually going on. Enjoy!
recent
- Matador: The Obvious MVC Framework for Node
- Sandboxing JavaScript
- Crouching Ender, hidden command
- Ender.js - The open submodule library
- Qwery - The Tiny Selector Engine
- Klass
- Smallest DOMReady code, ever.
- $script.js - Another JavaScript loader
- About that slowness on Twitter...
- Autocomplete Fuzzy Matching
- JavaScript Cache Provider
- JavaScript Animate
- Asynchronous method queue chaining in JavaScript
- Something changed
- Unofficial Twitter Widget Documentation
i am dustin diaz

