简体   繁体   中英

Different `on('message')` callback per MQTT topic in Node.js

I use MQTT.js. Is it possible to define a different callback per topic?

For example, I subscribe to topics a , b , and c and create an on message callback per topic like so:

client.on('message', 'a', cb)
client.on('message', 'b', cb)
client.on('message', 'b', cb)

If not, how can I work this around? Any solution is welcome.

No it is not possible.

You just need to add a if/else or switch block to your on message callback that uses the topic as the selector.

eg

client.on('message', function(topic, message) {
  switch(topic) {
    case 'a':
      ...
      break;
    case 'b':
      ...
      break;
    default:
      ...
  }
})

or store callback function in an object and use topics as the key eg

var callbacks = {}

callbacks["a"] = function(message) {...}

client.on('message', function(topic, message) {

  callbacks[topic](message)

})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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