1

How can I copy events from one group to another?

Html (note that .view has no event on purpose),

<div class="original">
    <a href="#" class="edit">edit</a>
    <a href="#" class="delete">delete</a>
    <a href="#" class="view">view</a>
</div>

<div class="copy">
    <a href="#" class="edit">edit</a>
    <a href="#" class="delete">delete</a>
    <a href="#" class="view">view</a>
</div>

jQuery:

var parent = $('.original');

$(".edit", parent).click(function(){
    return false;
});

$(".delete", parent).click(function(){
    return false;
});


$.each($._data($('.edit:first').get(0), 'events'), function() {
    // iterate registered handler of original
    $.each(this, function() {
      $('.edit:last').bind(this.type, this.handler);
    });
});

With this, I only manage to copy the event of .edit to another, but I have a lot more events to copy to another group.

Any ideas?

EDIT:

$("a").each( function(i, e) { 
    var $each = this;
    //console.log($._data($(this).get(0), 'events'));
    if($._data($(this).get(0), 'events') !== undefined){
        $.each($._data($($each).get(0), 'events'), function() {
            $.each(this, function() {
                $("." + $each.className, copy).unbind(this.type, this.handler).bind(this.type, this.handler);
            });
       });
    }
}); 
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Run
  • 54,938
  • 169
  • 450
  • 748

1 Answers1

0

According to jQuery's .clone() documentation there is a parameter just for this. So in your case, to clone a group and copy all events for all children you'll do something like this:

$(".original a.edit").on("click", function () {
    alert("edit clicked!");
});
$(".original a.delete").on("click", function () {
    alert("delete clicked!");
});
$(".original a.view").on("click", function () {
    alert("view clicked!");
});

var $clone = $(".whatever-your-container-is-called").clone(true);
$("#container").append($clone);

The bit doing the work is the .clone(true) where the argument name is withDataAndEvents.

Paul Aldred-Bann
  • 5,840
  • 4
  • 36
  • 55
  • @tealou I assumed you wanted to apply the events from one structure to a similar - is that your intention? In that case, yes this does copy the DOM structure too, which is fine if you can create the DOM structure? Or do you **need** to apply these events to an already existing DOM structure? – Paul Aldred-Bann Jan 22 '15 at 11:45
  • Yeah I need to apply the events to an updated DOM structure. The structure's text may be different from the **original** after updating. I sorta got it sorted - only with lots of `.each` which is not good I think! See my update. – Run Jan 22 '15 at 13:41