我只是想知道,在TypeScript中,您是否可以在类或接口上定义自定义事件?

这会是什么样子?

推荐答案

这个简化的事件用作属性如何?拥有类的类型更强,且无继承要求:

interface ILiteEvent<T> {
    on(handler: { (data?: T): void }) : void;
    off(handler: { (data?: T): void }) : void;
}

class LiteEvent<T> implements ILiteEvent<T> {
    private handlers: { (data?: T): void; }[] = [];

    public on(handler: { (data?: T): void }) : void {
        this.handlers.push(handler);
    }

    public off(handler: { (data?: T): void }) : void {
        this.handlers = this.handlers.filter(h => h !== handler);
    }

    public trigger(data?: T) {
        this.handlers.slice(0).forEach(h => h(data));
    }

    public expose() : ILiteEvent<T> {
        return this;
    }
}

这样使用:

class Security{
    private readonly onLogin = new LiteEvent<string>();
    private readonly onLogout = new LiteEvent<void>();

    public get LoggedIn() { return this.onLogin.expose(); } 
    public get LoggedOut() { return this.onLogout.expose(); }

    // ... onLogin.trigger('bob');
}

function Init() {
    var security = new Security();

    var loggedOut = () => { /* ... */ }

    security.LoggedIn.on((username?) => { /* ... */ });
    security.LoggedOut.on(loggedOut);

    // ...

    security.LoggedOut.off(loggedOut);
}

改进?

A gist for this

Typescript相关问答推荐

APP_INITIALIZER—TypeError:appInits不是函数

如何使函数接受类型脚本中具有正确类型的链接修饰符数组

如何使用函数填充对象?

访问继承接口的属性时在html中出错.角形

从TypeScrip中的其他类型检索泛型类型

为什么不能使用$EVENT接收字符串数组?

使用KeyOf和Never的循环引用

为什么Typescript不能推断类型?

找不到财产的标准方式?

在Mac和Windows上运行的Web应用程序出现这种对齐差异的原因是什么?(ReactNative)

根据类型脚本中的泛型属性 Select 类型

将带有样式的Reaction组件导入到Pages文件夹时不起作用

17个Angular 的延迟观察.如何在模板中转义@符号?

NPM使用Vite Reaction应用程序运行预览有效,但我无法将其部署到Netlify

在类型脚本中创建显式不安全的私有类成员访问函数

基于泛型的类型脚本修改类型

可以';t使用t正确地索引对象;联合;索引类型

覆盖高阶组件中的 prop 时的泛型推理

TS2532:对象可能未定义

为什么我们在条件语句中使用方括号[]?