1つの解決策は、追加されたリスナーを記憶するaddEventListenerの独自のラッパーを作成して、リスナーを「再生」できるようにすることです。
// set an event handler after memoizing it
function myAddEventListener(element, type, listener, useCapture) {
// store listeners as an array under element.listeners
if (!element.listeners) { element.listeners=[]; }
// each element of the array is an array of arguments to addEventListener
element.listeners[element.listeners.length] =
Array.prototype.slice.call(arguments,1);
// apply listener to element itself
element.addEventListener (type, listener, useCapture);
}
// copy a list of event handlers from one element to another
function copyEventListeners (from_element, to_element) {
var i;
if (from_element.listeners) {
for (i=0; i<from_element.listeners.length; i++) {
Element.addEventListener.apply (to_element, from_element.listeners[i]);
}
}
}
それで:
function clone_with_listeners (element) {
var cloned_element = element.cloneNode();
copyEventListeners (element, cloned_element);
return cloned_element;
}
Elementオブジェクトの元のメソッドを上書きすることを妨げる宗教的信念がない場合:
var orgAddEventListener = Element.addEventListener;
// our version of addEventListener
Element.addEventListener = function (type, listener, useCapture) {
// store listeners as an array under element.listeners
if (!this.listeners) { this.listeners=[]; }
// each element of the array is an array of arguments to addEventListener
this.listeners[element.listeners.length] =
Array.prototype.slice.call (arguments,0);
// apply listener to element itself
orgAddEventListener.call (element, type, listener, useCapture);
};
// copy a list of event handlers from this element to another
Element.copyEventListeners = function (to_element) {
var i;
if (from_element.listeners) {
for (i=0; i<this.listeners.length; i++) {
Element.addEventListener.apply (to_element, this.listeners[i]);
}
}
};
その後:
Element.cloneNode = function () {
var cloned_element = this.cloneNode();
this.copyEventListeners (cloned_element);
return cloned_element;
};