粘贴事件中的Typescript回调为null


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。我该如何更正?

我已经在提到的可能的副本中查看了这个问题,我不认为它与我在这里所做的事情有什么关系。

您丢失了this上下文,因为您使用了原型中未调用的类方法(this.pasteHandler((在RegisterEvent中(。

您需要进行以下编辑之一:

    public RegisterEvent() {
        // Use arrow function here
        window.addEventListener("paste", e => this.pasteHandler(e));
    }    

或此编辑:

// Use arrow function here
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);
    }
}

另见TypeScript";这个";在jquery回调中调用时的作用域问题

最新更新