1

我有一个使用普通 javascript 设置的事件处理程序,如下所示:

myElement.addEventListener('drop', handleDrop, false);

然后,在 handle drop 里面我尝试这样做:

var myContainer = $(this.parentNode);
myContainer.after(myContainer.clone(true, true));

但是,该事件似乎没有被转移到克隆元素。发生这种情况是因为我也没有将事件与 jQuery 绑定吗?

我试图通过将事件与 jQuery 绑定来测试这一点,但这不支持该dataTransfer对象,因此它破坏了其他代码。

4

1 回答 1

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;
};
于 2012-06-30T11:00:45.003 回答