Custom Event Example: Simple Publisher and Subscriber

Date: September 16, 2006

Component: Event, Dom

Version: v0.11.3

Click anywhere within the grey box to resize me.
Subscriber Div: Size changes will be reported here.

In this YDN-JavaScript post, mattesid requests a simple example of using Custom Event, part of the YUI Event Utility, to respond to changes in the size of a page element.

In this example, we'll have a grey container div within which is a blue resizer div. If you click in container, resizer will automatically resize to "x" position of your click. When this happens, the click hander will fire a Custom Event, onSizeChange, which will let other components on the page know about the change. We'll create one such component, a subscriber, that will write out to the subscriber div the new width of the resizer element.

Start with some simple CSS code for the appearing elements:

Next, dive into the script, of which the important bits are explored below (view source for full script). The script will also be quite simple, beginning with creating our Custom Event, which we'll fire when our click handler executes and changes the resizer's width.

Our click handler, to be fired when the grey container div is clicked on, looks like this; remember, it only fires the Custom Event if it seems like the click will result in a positive value for the resizer's new width — line 15 below is where we ultimately fire the Custom Event.

We now have a Custom Event and are firing it at the right time, passing in the relevant data payload: the new width of the resizer div. The last step is to create a function to respond to this change and then subscribe that function to our Custom Event, onSizeChange:

This is a simple example of how to use Custom Events. One of the powerful things about this concept is how far it can extend — obviously, we only have one subscriber here, but we could have from zero to n subscribers. Moreover, Custom Events give you granular control over scope and firing order. As a result of their flexibility and power, we find ourselves using Custom Events more and more as vehicles for exposing API functionality in YUI components.

Eric Miraglia, Yahoo Presentation Platform Engineering

(c)2006-2007 Yahoo Inc.