Reputation: 20895
In my Google Closure code, I want to assign an event to every single span in a div.
HTML:
<div id="container">
<span>foo</span>
<span>bar</span>
<span>bacon is delicious</span>
</div>
Closure Javascript:
var container = goog.dom.getElement('container');
var spans = goog.dom.getChildren(container);
for (var i = 0; i < spans.length; i++) {
eventHandler.listen(
spans[i],
goog.events.EventType.CLICK,
function (e) {
doSomeStuff(e.target);
}
}
This loop seems inefficient though because it seems to assign an event node to every single span element. Can I somehow assign a single event node to the containing div and have the callback function run when a click event on a span bubbles up to the containing div?
In jQuery, I believe the difference between the live()
and delegate()
functions parallels the issue I am dealing with here.
Upvotes: 3
Views: 511
Reputation: 22508
I never used Google Closure, but you are already using e.target
. By just adding one listener to the container you can obtain the actually clicked element by using e.target
.
var container = goog.dom.getElement('container');
eventHandler.listen(
container,
goog.events.EventType.CLICK,
function (e) {
doSomeStuff(e.target);
});
Upvotes: 3