I wrote a mqtt client.js, but realized I need multiple instances of this script so I rewrote it into a class. Now I ended up with a lot of 'this.foo' references vor my variables, which made me wonder, is this the correct way of using classes in javascript?
Here´s how part of my class looks like:
this.client = mqtt.connect("mqtts://" + this.host, options); // mqtts for tls connection
// client event handling
this.client.on("connect", () => {
log.write("LOG_INFO", "PubClient connected to Broker: " + this.host + ":" + this.settings.port);
this.client.publish("client/publisher/status", "online", { qos: 1, retain: true });
this.clientToSocket.pubConnect(true);
});
this.client.on("close", () => {
//log.write("LOG_INFO", "PubClient close");
});
this.client.on("disconnect", (packet) => {
log.write("LOG_INFO", "PubClient disconnected. Reasoncode: " + packet.reasoncode);
});
this.client.on("offline", () => {
log.write("LOG_INFO", "PubClient offline");
this.clientToSocket.pubConnect(false);
});
this.client.on("error", (err) => {
//log.write("LOG_ERR", "PubClient Error: " + err.message);
});
this.client.on("packetreceive", (packet) => {
//log.write("LOG_INFO", "PubClient packet received: " + packet.cmd);
});
}
}
publish(topic, qos, msg) {
if(this.client !== undefined) {
this.client.publish(topic, msg, { qos: parseInt(qos), retain: true });
//log.write("LOG_INFO", "Publishing Message with: topic: " + topic + " payload: " + msg);
} else {
log.write("LOG_ERR", "Error: Publish not possible because client undefined");
}
}
close() {
if(this.client !== undefined) {
this.client.end();
log.write("LOG_INFO", "PubClient closing");
}
}
}
You can simplify it, using local variables. When work is done can assign to this. You can also use restructure to use the variables.
Local Var
constructor() {
const client = mqtt.connect("mqtts://" + host, options); // mqtts for tls connection
client.on("close", () => {
//log.write("LOG_INFO", "PubClient close");
});
this.client = client;
}
De-Structure:
doSomthingOnClient() {
const {client} = this // destrcuture
client.get() // use it
}
Whole class:
class Client {
constructor() {
const client = mqtt.connect("mqtts://" + host, options); // mqtts for tls connection
client.on("connect", () => {
log.write(
"LOG_INFO",
"PubClient connected to Broker: " + host + ":" + settings.port
);
client.publish("client/publisher/status", "online", {
qos: 1,
retain: true,
});
clientToSocket.pubConnect(true);
});
client.on("close", () => {
//log.write("LOG_INFO", "PubClient close");
});
client.on("disconnect", (packet) => {
log.write(
"LOG_INFO",
"PubClient disconnected. Reasoncode: " + packet.reasoncode
);
});
this.client = client;
}
getClient() {
return this.client;
}
doSomthingOnClient() {
const {client} = this // destrcuture
client.get() // use it
}
}
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.