简体   繁体   English

MQTT Paho Javascript-是否可以为每个订阅定义处理函数?

[英]MQTT Paho Javascript - Is it possible to define a handlerfunction per subscription?

I am making a web application with MQTT Paho Javascript ( mqttws31.js ). 我正在使用MQTT Paho Javascript( mqttws31.js )制作Web应用程序。

in my onMessageArrived function I now define what message arrived by the following code: 在我的onMessageArrived函数中,我现在通过以下代码定义到达的消息:

    var topic = message.destinationName;
    var message = message.payloadString;
    var n = topic.lastIndexOf('/');
    var result = topic.substring(n + 1);
    switch(result){
      case "register":{
        //registerhandler
      }
      break;
      case "data":{
        //datahandler
      }
      break;
      default:{
        alert("wrong topic");
      }
    };

Is there a better way to check the topic? 有没有更好的方法来检查主题?

Is it possible to define a messageArrived function per subscription? 是否可以为每个订阅定义一个messageArrived函数? The only way I know to define the messageArrived is before the client.connect function. 我知道定义messageArrived的唯一方法是在client.connect函数之前。 And the only way I know to subscribe is after the connection to do client.subscribe . 而且我知道订阅的唯一方法是在连接完成client.subscribe

It would be very handy to define for example: client.subscribe("registertopic", registerhandlerfunction); 定义例如以下代码将非常方便: client.subscribe("registertopic", registerhandlerfunction);

What can I do? 我能做什么?

No, the client api doesn't provide this capability. 不可以,客户端api不提供此功能。

You have a couple options. 您有两种选择。 Either do as you are doing; 要么做就做,要么做。 hard code a series of if/then/elses or switch/cases. 硬编码一系列if / then / elses或switch / cases。 Or you could quite easily add your own wrapper to the client library that provides it a more generic capability. 或者,您可以很容易地将自己的包装器添加到为其提供更通用功能的客户端库中。

For example, the following untested code: 例如,以下未经测试的代码:

var subscriptions = [];
function subscribe(topic,callback) {
    subscriptions.push({topic:topic,cb:callback});
    mqttClient.subscribe(topic);
}

mqttClient.onMessageArrived = function(message) {
    for (var i=0;i<subscriptions.length;i++) {
        if (message.destinationName == subscriptions[i].topic) {
            subscriptions[i].cb(message);
        }
    }
}

Note, this assumes you only subscribe to absolute topics - ie without wildcards. 请注意,这假设您仅订阅绝对主题-即没有通配符。 If you use wildcards, you'd have to do some regular expression matching rather than the == test this code uses. 如果使用通配符,则必须进行一些正则表达式匹配,而不是此代码使用==测试。

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

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