exfm/touch-element

Event Delegation

Closed this issue · 1 comments

Is it possible to do event delegation on dynamic JS templates?

Something like this.. (doesn't work - example)

var dWrapper = new TouchElement($('#myWrapper')[0]);

$('#myWrapper').on('touched','span',function(e){
     console.log('event called');
});

Where all the spans that are dynamically generated via js templating are delegated with the touched event?
Or is it best after the html is generated - loop through and apply the custom touched event to all the spans like this -

$('#myWrapper span').each(function() {
    new TouchElement($(this)[0]);
});

The latter works; but for me it would be easier if I could use something like the former and delegate the event to be tied to all spans within the wrapper ID.

Thanks

If the new elements are children of the element you already attached a listener to, it will work. If they are completely new elements, you need to wait until they are created then add listeners to them.