Best way to add an event listener to save resources #3771
-
So i'm trying to know how javascript handles function. if i have a code like this: io.on("connection", function(socket) {
socket.on("hi", function(data) {
socket.emit("emit", "hey")
})
}) What's in my mind is that each new connection, javascript will create another function for the "hi" event. So what I'm currently doing in my app is like this: function hi(data) {
this.emit("emit", "hey")
}
io.on("connection", function(socket) {
socket.on("hi", hi)
}) This way javascript will just reuse the function hi instead of instancing a new one?? I'm not sure if this is necessary but I want to consume less resources as much as possible because I'm thinking about what will happen when the server have thousand of connections. If what i'm currently doing is correct, how do I implement this style without my code turning into spaghetti? Or is it really worth it to use this kind of coding to save memory resources? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Here's a common application structure:
const httpServer = require("http").createServer();
const io = require("socket.io")(httpServer);
const { createOrder, readOrder } = require("./orderHandler")(io);
const { updatePassword } = require("./userHandler")(io);
const onConnection = (socket) => {
socket.on("order:create", createOrder);
socket.on("order:read", readOrder);
socket.on("user:update-password", updatePassword);
}
io.on("connection", onConnection);
module.exports = (io) => {
const createOrder = function (payload) {
const socket = this; // hence the 'function' above, as an arrow function will not work
// ...
};
const readOrder = function (orderId, callback) {
// ...
};
return {
createOrder,
readOrder
}
} I've added it here: https://socket.io/docs/v3/server-application-structure/ |
Beta Was this translation helpful? Give feedback.
Here's a common application structure:
index.js
orderHandler.js