Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将socket.io事件分离到不同的文件中_Javascript_Node.js_Socket.io - Fatal编程技术网

Javascript 将socket.io事件分离到不同的文件中

Javascript 将socket.io事件分离到不同的文件中,javascript,node.js,socket.io,Javascript,Node.js,Socket.io,我在尝试将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

我在尝试将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:这基本上使用了与现在相同的策略。

这里有一个干净的解决方案,使用工厂将路线保留在你的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" });
    }
}

谢谢你,罗伊!这就是我要找的。