event.dataTransfer在setTimeout函数中丢失了它的项

时间:2013-05-22 07:33:58

标签: javascript javascript-events settimeout

有人可以解释为什么会这样。这是在ondrop处理程序

为什么它会在计时器中丢失它的值?

var _this = this;

this.event = event;

console.log(this.event.dataTransfer.items);
## DataTransferItemList {0: DataTransferItem, length: 1, item: function, clear: function, add: function}


setTimeout((function() {
  return console.log(_this.event.dataTransfer.items);
  ## DataTransferItemList {length: 0, item: function, clear: function, add: function}

}), 100);

即使这不起作用

var items, _items,
  _this = this;

items = event.dataTransfer.items;
_items = items;

setTimeout((function() {
  return console.log(_items);
}), 100);

2 个答案:

答案 0 :(得分:2)

如果我正确地阅读HTML5 Drag and dropdataTransfer对象仅在拖放期间与“拖动数据存储”相关联,有时它被解除关联或禁用,实际上表示items为空。

因此,event.dataTransfer只能在ondrop处理程序中使用,如果您需要保留超出您需要复制它们的项目(尽管我不确定复制项目会按预期工作,您可能需要立即提取所需的数据。)

答案 1 :(得分:0)

你的问题接缝是,当setTimeout计时器运行时,调用你的函数的this将不会是this,这将是window因此你需要如果您想要正确的行为,请更改它:

取自here使用此覆盖全局覆盖setTimeout和setInterval:

// Just place this lines in your javascript file
// Enable the passage of the 'this' object through the JavaScript timers
var __nativeST__ = window.setTimeout, __nativeSI__ = window.setInterval;
window.setTimeout = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
  var oThis = this, aArgs = Array.prototype.slice.call(arguments, 2);
  return __nativeST__(vCallback instanceof Function ? function () {
    vCallback.apply(oThis, aArgs);
  } : vCallback, nDelay);
};

window.setInterval = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
var oThis = this, aArgs = Array.prototype.slice.call(arguments, 2);
  return __nativeSI__(vCallback instanceof Function ? function () {
    vCallback.apply(oThis, aArgs);
  } : vCallback, nDelay);
};

然后您的功能将按预期工作:

...
console.log(this.event.dataTransfer);
## DataTransferItemList {0: DataTransferItem, length: 1, item: function, clear: function, add: function}

setTimeout((function() {
  return console.log(this.event.dataTransfer);
  ## DataTransferItemList {length: 0, item: function, clear: function, add: function}
}), 100);
...

希望有所帮助