繁体   English   中英

访问mqtt回调范围之外的类属性

[英]Access class properties outside of mqtt callback scope

我正在使用npm-mqtt从另一个mqtt代理获取数据。

在收到的每条消息上,我想将数据添加到类/组件数组属性。

但是我无法访问该类或其属性。 相反,范围显示我在mqtt客户端类对象中。

这是一个代码示例:

this.mydata: Array<any> = [];

private fetchWithMqtt(){
var client = mqtt.connect('ws://' + this.ip + ":" + Number(this.port) + "/mqtt");
        // set callback handlers
        client.on('close', this.onConnectionLost);
        client.on('message', this.onMessageArrived);
        client.on('connect', this.onConnect);
}

private onMessageArrived(topic, message) {
        let tempDataset = JSON.parse(message).dataset;
            this.mydata.push({ //this.mydata is undefined because this = mqtt-client
                x: tempDataset[0],
                y: tempDataset[1]
            });

如何在此范围之外将数据推送到类属性?

使用.bind(this) ,可以确保在调用事件时this不会改变。

您的代码现在将如下所示:

this.mydata: Array<any> = [];

private fetchWithMqtt(){
    var client = mqtt.connect('ws://' + this.ip + ":" + Number(this.port) + "/mqtt");
    // set callback handlers
    client.on('close', this.onConnectionLost.bind(this));
    client.on('message', this.onMessageArrived.bind(this));
    client.on('connect', this.onConnect.bind(this));
}

private onMessageArrived(topic, message) {
    let tempDataset = JSON.parse(message).dataset;
    this.mydata.push({
        x: tempDataset[0],
        y: tempDataset[1]
    });

但是,如果您需要在事件处理程序中访问client ,该怎么办? 好了,您仍然可以使用bind,但是将mydata放在事件处理程序的前面,并将其作为参数。

您的代码现在变为:

this.mydata: Array<any> = [];

private fetchWithMqtt(){
    var client = mqtt.connect('ws://' + this.ip + ":" + Number(this.port) + "/mqtt");
    // set callback handlers
    client.on('close', this.onConnectionLost.bind(client, this.mydata));
    client.on('message', this.onMessageArrived.bind(client, this.mydata));
    client.on('connect', this.onConnect.bind(client, this.mydata));
}

private onMessageArrived(mydata, topic, message) {
    let tempDataset = JSON.parse(message).dataset;
    mydata.push({ // this == client
        x: tempDataset[0],
        y: tempDataset[1]
    });

暂无
暂无

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

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