YUI 2.X: Using Event Component

0
96
7 min read

 

Yahoo! User Interface Library 2.x Cookbook

Yahoo! User Interface Library 2.x Cookbook: RAW

Over 70 simple incredibly effective recipes for taking control of Yahoo! User Interface Library like a Pro

 
  • Easily develop feature-rich internet applications to interact with the user using various built-in components of YUI library
  • Simple and powerful recipes explaining how to use and implement YUI 2.x components
  • Gain a thorough understanding of the YUI tools
  • Plenty of example code to help you improve your coding and productivity with the YUI Library
  • Hands-on solutions that takes a practical approach to recipes

 


        Read more about this book      

(For more resources on YUI, see here.)

Introduction

In this article, you will learn how to use YUI to handle JavaScript events, what special events YUI has to improve the functionality of some JavaScript events, and how to write custom events for your own application.

Using YUI to attach JavaScript event listeners

When attaching events in JavaScript most browsers use the addEventListener function , but the developers of IE use a function called attachEvent. Legacy browsers do not support either function, but instead require developers to attach functions directly to element objects using the ‘on’ + eventName property (for example myElement.onclick=function(){…}). Additionally, the execution context of event callback functions varies depending on how the event listener is attached. The Event component normalizes all the cross-browser issues, fixes the execution context of the callback function, and provides additional event improvements. This recipe will show how to attach JavaScript event listeners, using YUI.

How to do it…

Attach a click event to an element:

var myElement = YAHOO.util.Dom.get('myElementId');
var fnCallback = function(e) {
alert("myElementId was clicked");
};
YAHOO.util.Event.addListener(myElement, 'click', fnCallback);

Attach a click event to an element by its ID:

var fnCallback = function(e) {
alert("myElementId was clicked");
};
YAHOO.util.Event.addListener('myElementId','click',fnCallback)

Attach a click event to several elements at once:

var ids = ["myElementId1", "myElementId2", "myElementId3"];
var fnCallback = function(e) {
var targ = YAHOO.util.Event.getTarget(e);
alert(targ.id + " was clicked");
};
YAHOO.util.Event.addListener(ids, 'click', fnCallback);

When attaching event listeners, you can provide an object as the optional fourth argument, to be passed through as the second argument to the callback function:

var myElem = YAHOO.util.Dom.get('myElementId');
var fnCallback = function(e, obj) {
alert(obj);
};
var obj = "I was passed through.";
YAHOO.util.Event.addListener(myElem,'click',fnCallback,obj);

When attaching event listeners, you can change the execution context of the callback function to the fourth argument, by passing true as the optional fifth argument:

var myElement = YAHOO.util.Dom.get('myElementId');
var fnCallback = function(e) {
alert('My execution context was changed.');
};
var ctx = {
/* some object to be the execution context of callback */
};
YAHOO.util.Event.addListener(
myElement, 'click', fnCallback, ctx, true);

How it works…

The addListener function wraps the native event handling functions, normalizing the cross- browser differences. When attaching events, YUI calls the correct browser specific function, or defaults to legacy event handlers. Before executing the callback function, the Event component must (in some browsers) find the event object and adjust the execution context of the callback function. The callback function is normalized by wrapping it in a closure function that executes when the browser event fires, thereby allowing YUI to correct the event, before actually executing the callback function.

In legacy browsers, which can only have one callback function per event type, YUI attaches a callback function that iterates through the listeners attached by the addListener function

There’s more…

The addListener function returns true if the event listener is attached successfully and false otherwise.

If the element to listen on is not available when the addListener function is called, the function will poll the DOM and wait to attach the listener when the element becomes available.

Additionally, the Event component also keeps a list of all events that it has attached. This list is maintained to simplify removing events listeners, and so that all event listeners can be removed when the end-user leaves the page.

Find all events attached to an element:

var listeners = YAHOO.util.Event.getListeners('myElementId');
for (var i=0,j=listeners.length; i<j; i+=1) {
var listener = listeners[i];
alert(listener.type); // event type
alert(listener.fn); // callback function
alert(listener.obj); // second argument of callback
alert(listener.adjust); // execution context
}

Find all events of a certain type attached to an element:

// only click listeners
var listeners =
YAHOO.util.Event.getListeners('myElementId', 'click');

The garbage collector in JavaScript does not always do a good job cleaning up event handlers. When removing nodes from the DOM, remember to remove events you may have added as well.

More on YAHOO.util.Event.addListener

The addListener function has been aliased by the shorter on function:

var myElement = YAHOO.util.Dom.get('myElementId');
var fnCallback = function(e) {
alert("myElementId was clicked");
};
YAHOO.util.Event.on(myElement, 'click', fnCallback);

By passing an object in as the optional fifth argument of addListener, instead of a Boolean, you can change the execution context of the callback to that object, while still passing in an another object as the optional fourth argument:

var myElement = YAHOO.util.Dom.get('myElementId');
var fnCallback = function(e, obj) {
// this executes in the context of 'ctx'
alert(obj);
};
var obj = "I was passed through.";
var ctx = {
/* some object to be the execution context of callback */
};
YAHOO.util.Event.addListener(
myElement,'click',fnCallback,obj, ctx);

Lastly, there is an optional Boolean value that can be provided as the sixth argument of addListener, which causes the callback to execute in the event capture phase, instead of the event bubbling phase. You probably won’t ever need to set this value to true, but if you want to learn more about JavaScript event phases see: http://www.quirksmode.org/js/events_order.html

Event normalization functions

The event object, provided as the first argument of the callback function, contains a variety of values that you may need to use (such as the target element, character code, etc.). YUI provides a collection of static functions that normalizes the cross-browser variations of these values. Before trying to use these properties, you should read this recipe, as it walks you through each of those functions.

How to do it…

Fetch the normalized target element of an event:

var fnCallback = function(e) {
var targetElement = YAHOO.util.Event.getTarget(e);
alert(targetElement.id);
};
YAHOO.util.Event.on('myElementId', 'click', fnCallback);

Fetch the character code of a key event (also known as the key code):

var fnCallback = function(e) {
var charCode = YAHOO.util.Event.getCharCode(e);
alert(charCode);
};
YAHOO.util.Event.on('myElementId', 'keypress', fnCallback);

Fetch the x and y coordinates of a mouse event:

var fnCallback = function(e) {
var x = YAHOO.util.Event.getPageX(e);
var y = YAHOO.util.Event.getPageY(e);
alert("x-position=" + x + " and x-position= " + y);
};
YAHOO.util.Event.on('myElementId', 'click', fnCallback);

Fetch both the x and y coordinates of a mouse event, using:

var fnCallback = function(e) {
var point = YAHOO.util.Event.getXY(e);
alert("x-position="+point[0]+" and x-position= "+point[1]);
};
YAHOO.util.Event.on('myElementId', 'click', fnCallback);

Fetch the normalized related target element of an event:

var fnCallback = function(e) {
var targetElement = YAHOO.util.Event.getRelatedTarget(e);
alert(targetElement.id);
};
YAHOO.util.Event.on('myElementId', 'click', fnCallback);

Fetch the normalized time of an event:

var fnCallback = function(e) {
var time = YAHOO.util.Event.getTime(e);
alert(time);
};
YAHOO.util.Event.on('myElementId', 'click', fnCallback);

Stop the default behavior, propagation (bubbling) of an event, or both:

var fnCallback = function(e) {
// prevents the event from bubbling up to ancestors
YAHOO.util.Event.stopPropagation(e);
// prevents the event's default
YAHOO.util.Event.preventDefault(e);
// prevents the event's default behavior and bubbling
YAHOO.util.Event.stopEvent(e);
};
YAHOO.util.Event.on('myElementId', 'click', fnCallback);

How it works…

All of these functions test to see if a value exists on the event for each cross-browser variation of a property. The functions then normalize those values and return them. The stopPropogation and preventDefault functions actually modify the equivalent cross-browser property of the event, and delegate the behavior to the browsers.

LEAVE A REPLY

Please enter your comment!
Please enter your name here