Paho Javascript MQTT 订阅多个主题

Paho Javascript MQTT subscribe to multiple topics

是否可以使用与 paho python 中使用的 message_callback_add 类似的概念(在 javascript 中)在客户端订阅多个主题时使用多个回调?我在 onMessageArrived() 中看到了 if 条件的使用,但我想知道是否存在更有效和更干净的方法?

var mqtt;                           // MQTT variable/object
var reconnectTimeout = 5000;        // 5 seconds for the reconnectTimeout
var host="localhost";               // MQTT bridge IP
var port=8083;                      // MQTT bridge port 
MQTTconnect();                      // Initialise the MQTT connections

function MQTTconnect(){
  console.log("mqtt connecting to " + host + ":" + port);
  mqtt = new Paho.MQTT.Client(host, port, "client_test");
  var options = {
    timeout: 100,
    onSuccess: onConnect,
    onFailure: onFailure,
  };
  mqtt.onMessageArrived = onMessageArrived;
  mqtt.connect(options); // connect
}

function onConnect(){
  console.log("Mqtt Connected - Subscribe to the topics");
  mqtt.subscribe("topic1/a");
  mqtt.subscribe("topic2/b");
}
            
function onFailure(message){
  console.log("Connection attempt to MQTT " + host + " failed");
  setTimeout(MQTTconnect, reconnectTimeout);
}

function onMessageArrived(msg){
  if (msg.destinationName == "topic1/a"){
    console.log("Topic1: ", msg.payloadString);
  }
  else if (msg.destinationName == "topic2/b"){
    console.log("Topic2: ", msg.payloadString);
  }
}

没有,JavaScript中的所有消息只有一个回调。

唯一的选择是在onMessageArrived回调

中根据需要检查主题和分支

图书馆可能没有,自己做回调逻辑吧!这是一个漂亮的解决方案:

import EventEmitter from 'events';
const emitter = new EventEmitter();

client.subscribe('my_topic_1');
client.subscribe('my_topic_2');
client.onMessageArrived = onMessage;

function onMessageArrived(message) {
   emitter.emit(message.topic, message.payloadString);
}

function subscribe(event, callback) {
   emitter.addListener(event, callback);
}

function unsubscribe(event, callback) {
   emitter.removeListener(event, callback);
}

subscribe('my_topic_1', (string) => {
   console.log('only my_topic_1 messages', string);
});