0

I'm using the MQTT npm module. When fires the myMqttObj.on('close',...) event I call myMqttObj.end() and then reassign it with a new connection:

 myMqttObj= mqtt.connect(....)

In this way all the previous myMqttObj.on() methods are listening on the new emitter. All this works great.

Now I'm trying to create my own method to create a new MQTT connection with the same npm module. I want only to hide the MQTT connection parameter calling a custom method with a simple string as a parameter:

var mySDK= require('./mySDK');
mySDK.mqttConnect("input",function(_inMqtt){
    if(_inMqtt!=null){
        inMqtt=_inMqtt;  //inMqtt is a global variable

        inMqtt.on('connect', function() {
           //do something here
        });

        inMqtt.on('close', function() {
            inMqtt.end();
            mySDK.mqttConnect("input",function(_inMqtt){
                inMqtt=_inMqtt;  //this assignment to the same Client object doesn't work
            });
        });
});

the mqttConnect method simply call the mqtt.connect method and return the Client object.

I expect that all the inMqtt.on() function are now listening on the new Client object, instead no event is catched. What's the problem?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Nicola
  • 465
  • 2
  • 7
  • 19
  • "*reassign it with a new connection: `myMqttObj = mqtt.connect(....)`. In this way all the previous myMqttObj.on() methods are listening on the new emitter*" That's absolut non-standard behaviour. An new object, a new instance, always means new listeners to be initialised. If you have not misinterpreted what you're seeing, they're doing really dodgy things - or the call isn't actually creating a new instance, but returns the old one. This should be documented in their API. – Bergi Jul 11 '17 at 04:49
  • Yes, it's strange, and now I think that it's right it doesn't work.. I've solved creating new listeners with the new object – Nicola Jul 11 '17 at 12:45

0 Answers0