Skip to main content
Version: 4.x

应用结构

注册事件处理程序

¥Registering event handlers

你将在下面找到有关如何注册事件处理程序的两条建议。

¥You will find below two suggestions on how to register your event handlers.

请注意,这些只是建议,而不是你必须遵循的严格准则。请根据自己的喜好进行调整!

¥Please note that these are merely suggestions and not strict guidelines that you must follow. Please adapt it to your own liking!

每个文件注册自己的事件处理程序

¥Each file registers its own event handlers

在这里,入口点保持整洁,但事件监听器可能不太容易被发现(尽管强大的命名约定/ctrl+f 会有所帮助)。

¥Here, the entrypoint is kept tidy, but the event listeners may be less discoverable (though strong naming convention/ctrl+f will help).

index.js

const httpServer = require("http").createServer();
const io = require("socket.io")(httpServer);

const registerOrderHandlers = require("./orderHandler");
const registerUserHandlers = require("./userHandler");

const onConnection = (socket) => {
registerOrderHandlers(io, socket);
registerUserHandlers(io, socket);
}

io.on("connection", onConnection);

orderHandler.js

module.exports = (io, socket) => {
const createOrder = (payload) => {
// ...
}

const readOrder = (orderId, callback) => {
// ...
}

socket.on("order:create", createOrder);
socket.on("order:read", readOrder);
}

所有事件处理程序都注册在 index.js 文件中

¥All event handlers are registered in the index.js file

在这里,每个事件名称都位于同一位置,这对于可发现性很有帮助,但在中型/大型应用中可能会失控。

¥Here, each event name is located in the same place, which is great for discoverability, but could get out of hand in a medium/big application.

index.js

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);

orderHandler.js

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
}
}