PDA

View Full Version : Event delegation and "sliding door" links.



jlizarraga
08-07-2009, 11:16 PM
Hi all,

Suppose I have the following markup:



<div id="demo">
<a id="sd1" href="#"><em>Sliding Door Link #1</em></a>
<a id="sd2" href="#"><em>Sliding Door Link #2</em></a>
</div>


Using a JS library like jQuery (I use YUI2/3 mostly but feel free to leave any responses in jQuery/mootools/etc. syntax!), I want to attach a single event listener to #demo and take advantage of event bubbling/delegation.

The event handler inspects ids to figure out what was clicked on. This means that if you click on an EM element within the link, the event handler will never know that one of the sliding door links was clicked.

Can anyone recommend a clean solution to this issue that preserves the single event handler/event delegation?

The half-solution I have come up with in my code is to create a faux-event object using the parentNode when an EM is encountered, which works fine but seems a bit too hacky. Here is an example of that (YUI3 event utility syntax here):



var clickHandler = function(e){
switch(e.target.get('id')){
case 'sd1':
alert('sd1 clicked.');
break;
case 'sd2':
alert('sd2 clicked.');
break;
default:
switch(e.target.get('nodeName')){
case 'EM':
var oE = {
target: e.target.get('parentNode'),
};
that.clickHandler(oE);
break;
default:
return true;
}
}
}; // clickHandler()


Thanks!