繁体   English   中英

使用 function 参数添加 EventListener

[英]Adding an EventListener with an function argument

我想向按钮添加事件侦听器。 应在单击时调用的 function 作为参数传递。 所以看起来像这样

public addButton(argFunction: Function) {
        const button: HTMLElement = document.createElement("button")

        button.addEventListener("click", argFunction);
    }

myclass.addButton(function(){
        console.log("test");
});

尝试以这种方式添加事件侦听器会导致 TypeScript 说“无法将类型“函数”的参数分配给类型为“(this:HTMLElement,ev:MouseEvent)=> any”的参数(由我粗略翻译)。

当我在 addButton 中声明一个 function 时,它可以工作:

public addButton(argFunction: Function) {
        const button: HTMLElement = document.createElement("button")

        var f = function () {
            console.log("f")
        };

        button.addEventListener("click", argFunction);
    }

为什么这行得通,我如何将 function 作为参数传递?

只需为您的听众 function 使用其他类型:


type Listener = (ev: MouseEvent) => void

// alternative way
interface Listener2 {
  (ev: MouseEvent): void
}


class Foo {
  public addButton(argFunction: Listener) {
    const button: HTMLElement = document.createElement("button")

    button.addEventListener("click", argFunction);
  }
}
const foo = new Foo()

foo.addButton(function () {
  console.log("test");
});

操场

尽量避免使用大写的构造函数类型,例如FunctionStringNumberObject

在 99% 的情况下,最好使用type Fn = (...args:any[])=>any而不是Function

我意识到像 String 这样的类型显示错误而不是字符串。 它们之间有区别吗?

是的,这是有区别的。 String , Number是构造函数类型,很像Array 但是当你创建一个像foo这样的简单字符串时,你不会使用String构造函数,比如String('foo') 您只需使用文字foo

请参阅文档

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM