Travis J
Travis J

Reputation: 82277

How to retain this jQuery event handler?

I have an click even handler on a dom element.

jQcurrentOption.click(function () {
 //IMPLEMENTATION
});

When this element is cloned .cloneNode(true) it loses its event handler :(. I know that I can change the jQuery (note I am still using 1.4.4 hence live and not bind(1.7+))

jQcurrentOption.live("click",function(){
 //IMPLEMENTATION
});

However I was curious if there was a way to retain these handlers without defining them with live (or bind). Sometimes I don't have the benefit of using jQuery to apply live.

Upvotes: 1

Views: 499

Answers (1)

Tomalak
Tomalak

Reputation: 338178

Have you tried jQuery's clone()?

var $clone = jQcurrentOption.clone(true);

It clones the event handlers if you pass true as an argument.


Apart from that, jQuery 1.4.4 supports delegate(), which is equivalent to 1.7's on():

$("select").delegate("option.current", "click", function () {
 //IMPLEMENTATION
});

This way your individual elements don't need to copy event handlers.


Just to make a point: Even though delegate() is deprecated with as of 1.7, it really is the same thing as the more modern on(), the only difference being the argument order. Here's the current implementation (1.7.2):

delegate: function( selector, types, data, fn ) {
  return this.on( types, selector, data, fn );
} 

Upvotes: 2

Related Questions