将 socket.io 个事件分成不同的文件

Separating socket.io events into different files

我在尝试将 socket.io 事件单独放入不同文件时遇到问题 而不是 将所有内容放入单个文件,即 app.js;

// app.js

io.on('connection', function(socket) {

    socket.on("helloword", require("./controllers/socket/helloworld"));
    // a bunch of other events
});

// controllers/socket/helloworld.js

module.exports = function(data) {

    if (data)
        socket.emit('response', { lorem: "ipsum" });
}

问题是 socket.io 没有将 "socket" 变量传递给所需的函数,因此我无法将响应发送回给用户,因此我采用了此解决方法;

// app.js

io.on("connection", function(socket) {

    // socket.io("helloworld", require("./controllers/socket/helloworld")(socket));
    // although the code above prints successfully console.log(socket) invoked at
    // the required file but as soon as its printed socket.io throws " TypeError: 
    // listener must be a function.
    require("./controller/socket/helloworld")(socket);
    // a bunch of other events
});

// controllers/socket/helloworld.js

module.exports = function(socket) {

    socket.on("helloworld", function(data) {

        if (data)
            socket.emit('response', { lorem: "ipsum" });
    }

    // others events regarding the same subject by the file.
}

我仍然认为这不是一个好的做法或最可靠的做法。我也无法通过 socket.io 文档找到解决问题的方法,也没有找到帮助我解决问题的相关问题。

PS: 这个question 基本和现在用的一样战术

这是一个干净的解决方案,使用工厂将路线保存在您的 app.js 中:

// app.js
io.on('connection', function(socket) {

    socket.on("helloword", require("./controllers/socket/helloworld")(socket));
    // a bunch of other events
});

// controllers/socket/helloworld.js
module.exports = function(socket){
    return function(data) {
        if (data) socket.emit('response', { lorem: "ipsum" });
    }
}