PDA

View Full Version : Creating A Lot Of Listeners



thejoker101
6 Nov 2006, 12:59 PM
This question is a 'how should I go about doing this thing' kind of question.

I have code that takes a few filter options and sends them to a php script via an ajax call and returns a list of images and places that list in the page. I'd like to have a listener on each one of those images. What is the best way to go about doing this?

I was thinking that once the html is inserted into the page, i can do a search for a class that i put on each image and then add a listener to each image that way, but that seems like that is pretty cumbersome and that there should be an easier/better way of doing it.

Does this question make sense?

jack.slocum
6 Nov 2006, 4:49 PM
You'd want to use event delegation for something like this. Check out the YAHOO.ext.View class, it will handle delegation for you automatically.

For manual delegation:

1. Add listener to a container element for the desired event

getEl('container').mon('click', clickHandler);

2. In your handler function, find the event source (the css class is optional):


var clickHandler = function(e){
var source = e.findTarget('someCssClass', 'someTag');
if(source){ // make sure they actually clicked on one of your elements

}
}

Event delegation is the preferred way to do something like this and it net much better performance.