How to clone the jQuery Listen plugin event?

I have some elements <tr>

on my page with an event click()

attached to an image that is inside each one. I am using this code

$(this).clone(true).appendTo("table#foo");

      

do the following:

  • copy those <tr>

    to another table
  • keep click events on images inside <tr>

    (because of the argument true

    )

This all works great. I have now added jQuery Listen for these <tr>

s so that the user does not need to target precisely: he / she can click anywhere <tr>

and I can transmit the click to the image.

It is coded like this:

$('tr.record').listen('click','td',function(){
  $(this).parent().find("img.clickable").click();
});

      

The listen () event works fine on the original element, but on the cloned element, the listen () event fails. The image click event still works fine.

This is what Firebug tells me:

m(this, e.type) is undefined

      

... and it references line 9 jquery.listen-1.0.3-min.js.

How can I get the listen () function to work with cloned elements?

Update

By default jQuery doesn't copy events on cloned elements, but this plugin is made for that.

Meanwhile, the author of the listen () plugin suggested a different strategy - see my answer below.

+1


source to share


1 answer


Ariel Flesler, creator of the listen () plugin, gave me this advice via email:

"I think there is a different way to solve this. The idea behind Listen (and event delegation) is to actually avoid all copies of events for new items."

"You could just do:"

$('table#foo').listen('click','td',function(){
 $(this).parent().find("img.clickable").click();
});

      



"Or even:"

$.listen('click','td',function(){
 $(this).parent().find("img.clickable").click();
});

      

"The first example will use a table as a listener. In the second, a tag is used <html>

. So whether or not you add new tables to td / tr /. This will still work."

+1


source







All Articles