handler - MQTT Paho Javascript - Is it possible to define a handlerfunction per subscription? -


i making web application mqtt paho javascript (mqttws31.js).

in onmessagearrived function define message arrived following code:

    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 better way check topic?

is possible define messagearrived function per subscription? way know define messagearrived before client.connect function. , way know subscribe after connection client.subscribe.

it handy define example: client.subscribe("registertopic", registerhandlerfunction);

what can do?

no, client api doesn't provide capability.

you have couple options. either doing; hard code series of if/then/elses or switch/cases. or quite add own wrapper client library provides more generic capability.

for example, following untested code:

var subscriptions = []; function subscribe(topic,callback) {     subscriptions.push({topic:topic,cb:callback});     mqttclient.subscribe(topic); }  mqttclient.onmessagearrived = function(message) {     (var i=0;i<subscriptions.length;i++) {         if (message.destinationname == subscriptions[i].topic) {             subscriptions[i].cb(message);         }     } } 

note, assumes subscribe absolute topics - ie without wildcards. if use wildcards, you'd have regular expression matching rather == test code uses.


Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -