【发布时间】:2015-06-26 20:08:28
【问题描述】:
interface myCallbackType { (dataType: string): void }
class PasteUtilities {
public myCallback: myCallbackType;
public pasteHandler(e) {
var items = e.clipboardData.items;
for (var i = 0; i < items.length; i++) {
console.log('file received');
this.myCallback(items[i].type);
}
}
public RegisterEvent() {
window.addEventListener("paste", this.pasteHandler);
}
}
var utils = new PasteUtilities();
utils.myCallback = function (dataType: string) {
console.log('Filetype: ' + dataType);
}
utils.RegisterEvent();
utils.myCallback('test type'); //test to make sure it's wired up right
这段代码的目的是在将文件粘贴到浏览器中时运行一些函数。要运行的函数存储在myCallback中。
我的测试顺序是访问页面并粘贴单个文件。这是粘贴 png 文件时的预期输出。
Filetype: test type
file received
Filetype: image/png
这是我的实际输出:
Filetype: test type
file received
Uncaught TypeError: this.myCallback is not a function
我猜是浏览器的粘贴事件的上下文不一样,所以myCallback为null。我该如何纠正这个问题?
我在possible duplicate mentioned 中查看了这个问题,但我看不出它与我在这里所做的事情有什么关系。
【问题讨论】:
标签: javascript callback typescript this