Flight has a great eventing system, and makes it easy to setup event handlers for component nodes. However, a couple things eluded me when trying to respond to delegated events for nodes that contained dynamic elements.
Here's the situation:
<div class="component">
<ul id="list">
<!-- dynamic elements show here -->
</ul>
</div>
and the component:
var ItemComponent = (function() {
function ItemComponent() {
this.defaultAttrs({
listSelector: '#list',
itemSelector: '#list li'
});
this.addItem = function(ev, params) {
var item = $('<li>'),
link = $('<a href="#">').html(params.content);
this.select('listSelector').append(item.append(link));
};
this.itemClick = function(ev, params) {
console.log("Item clicked: target=", ev.target);
console.log("Item clicked: currentTarget=", ev.currentTarget);
};
this.after('initialize', function() {
this.on(document, 'uiAddListItem', this.addItem);
this.on('click', { 'itemSelector': this.itemClick });
});
}
return flight.component(ItemComponent);
})();
$('#add-item-btn').on('click', function(){
$(document).trigger('uiAddListItem', {
content: $('input[name="item-content"]').val()
});
});
ItemComponent.attachTo('.component');
This basically just let's the user add li
items to a list. Each <li>
has content that is wrapped in an <a>
element. However, when the handler runs, we'd like to access the actual <li>
element and not the <a>
element that received the click event.
In the itemClick
handler, the event.target
element is the one that received the click, in this case the <a>
element. And the event.currentTarget
is the actual component the events are bound too (<div class="component">
).
How do you get the delegated, dynamic <li>
element in this case?
Here's the working JSBin