【问题标题】:Typescript callback is null from paste event来自粘贴事件的打字稿回调为空
【发布时间】: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


    【解决方案1】:

    您丢失了 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 "this" scoping issue when called in jquery callback

    【讨论】:

    • 是的,它确实澄清了。我发现这种语法令人困惑。我看过一段视频,其中 Anders 演示了围绕 this 的一些问题,但我想我并没有完全理解其后果。
    猜你喜欢
    • 2020-04-24
    • 2016-12-28
    • 1970-01-01
    • 1970-01-01
    • 2017-09-23
    • 1970-01-01
    • 1970-01-01
    • 2021-10-07
    • 1970-01-01
    相关资源
    最近更新 更多