Using an EventProvider

For the Client-Side Storage problem that I have been working on with YUI, I was introduced to the EventProvider Interface, which provides a better way of handling the CustomEvents attached to an object. In Yahoo!s own words:

EventProvider is designed to be used with YAHOO.augment to wrap CustomEvents in an interface that allows events to be subscribed to and fired by name. This makes it possible for implementing code to subscribe to an event that either has not been created yet, or will not be created at all.

By using this interface, developers no longer need to worry about whether or not a given CustomEvent exists when subscribing to it. Thereby, making coding easier, while allowing a developer the opportunity to not create CustomEvents that never fire. Additionally, EventProvider normalizes interactions with CustomEvents attached to objects, since the same methods will be attached to each object. Lastly, the events are bound to the augmented object, so although you might instantiate hundreds of EventProvider augmented object, each sharing an event named update, only the callback functions subscribed to the current object will execute when the fireEvent function of that object is called. In summary, when using EventProvider the event names need only be unique on a single object, not across all objects (as with CustomEvent).

Example 1: Methods Augmented to an Object

createEvent - used to create an event; should be created before calling fireEvent
fireEvent - fires the event, executing the proper subscribed functions
hasEvent - evaluates if an event exists
subscribe - associates a callback function with a given event
unsubscribe - unassociate a callback function with a given event
unsubscribeAll - unassociates all callback functions for a given event

Each of these method is explained in more detail in the YUI EventProvider API Docs. They all require an event name as the first parameter, otherwise behaving like their counterparts on the CustomEvent object. I recommend storing the event names as constants attached to the function prototype of the augmented object, that way they are easy to change and easy to use since they are attached to each instantiated object.

Example 2: Augmenting an Object with EventProvider

var MyObject = function() {
MyObject.prototype = {
	CE_UPDATE: update,
	doSomething: function() {
		/* your code */

YAHOO.lang.augmentProto(MyObject , YAHOO.util.EventProvider);

var myObject = new MyObject();
myObject.subscribe(myObject.CE_UPDATE, function() {
	/* your callback code */

Example 2 shows how to create a CE_UPDATE event, and fire a CE_UPDATE event, augment the object MyObject with EventProvider (without this fireEvent nad createEvent will fail), and subscribe a callback function to the CE_UPDATE (update) event. In the future I plan to use this event model for all my CustomEvents.