【发布时间】:2020-10-16 04:33:54
【问题描述】:
我正在制作一个应用来管理我家的一些智能灯。
我创建了一个非常简单的Broker 类。
import * as aedes from 'aedes';
import * as net from 'net';
export class Broker {
aedes: aedes.Aedes;
broker: net.Server;
port: number;
constructor(port: number){
this.aedes = aedes();
this.broker = net.createServer(this.aedes.handle);
this.port = port;
this.broker.listen(this.port, () => {
console.log('MQTT is listening.');
});
}
/**
* This is a callback register function
*
* Callback function must have a signature of type : function(topic: string, payload: string)
**/
onMsgReceived(callback: {(topic: string, payload: string): void}){
this.aedes.on('publish', (packet, client) => {
if (packet.cmd != 'publish') return;
callback(packet.topic, packet.payload.toString());
});
}
}
然后,例如,Test 类。
export Test {
someVar: string;
constructor(){ }
onMsgReceivedCallback(topic: string, payload: string){
console.log('Hey, i\'m printed from the test class');
console.log('And this is some var : ' + this.someVar);
}
}
当然还有index.ts 脚本。
import { Broker } from './broker.ts'
import { Test } from './test.ts'
const broker = new Broker(1883);
const test = new Test();
broker.onMsgReceived(test.onMsgReceivedCallback);
问题是,如果在函数 test.onMsgReceived 中我想调用类的成员,比如 var someVar,节点会抛出以下错误:
TypeError: Cannot read property 'testVar' of undefined
我不明白我该如何解决这个错误... 你有什么想法吗?
【问题讨论】:
标签: node.js typescript class callback mqtt