typescript - 打字稿设置功能成员和使用这个
问题描述
我正在使用打字稿开发一个电子应用程序。我的 main.ts 创建了我自己的 CommunicationProvider 类的对象。我想让这个类声明几个方法(在它正在实现的接口中定义),但在我的 main.ts 中设置这些方法的实际实现。所以我宣布我的班级为:
export class SocketIOInterceptionProvider implements IInterceptionProvider {
// IInterfaceProvider methods
show: (x?: number, y?: number) => void;
hide: () => void;
move: (x: number, y: number) => void;
constructor(port: number = 3000) {
this.initHttpServer(port);
}
public initHttpServer(port: number): void {
this._express.get('/show', function(req, res) {
console.log('SHOW from ' + req.ip);
if (this.show) this.show();
});
}
}
在 main.ts 我设置了实现:
const provider: SocketIOInterceptionProvider = new
SocketIOInterceptionProvider();
provider.show = (x?: number, y?: number) => { //show electron win}
在运行时 - 我的函数没有被触发,因为 'this' 未定义,当我点击:
if (this.show) this.show();
我怎样才能保持“这个”?是否有任何其他推荐的方式来处理来自 TS 类的事件?
解决方案
'this' 在快速回调中丢失了,所以我将它分配给一个局部变量以在快速回调中使用:
public initHttpServer(port: number): void {
this._express = express();
this._httpServer = this._express.listen(port);
const provider=this;
this._express.get('/show', function(req, res) {
console.log('SHOW from ' + req.ip);
if (provider.show) provider.show();
});
推荐阅读
- python-3.x - 在 python 中安装 feeder/feedr 库时出错
- vue-cli - 如何防止vue-cli项目自动添加分号
- c# - 如何复制 Nuget 包依赖项
- linux-kernel - Linux 内核是否为驱动程序开发人员提供了一种机制来处理低功耗情况?
- azure - 如何创建变量并将其设置为等于特定 customEvent 的计数?
- google-sheets - 如何将主题和内容拆分为多行?
- python - 当 python 2x 是您的默认 python 版本但您在 Bash 上使用 python 3x 时,如何在 pip 上安装 Django 2x
- database - 用 laravel 连接多个数据库
- php - 使用utf 8从android发送html post json数组到php并输入到数据库?
- c++ - 向量
> 运营商