我可以将 socket.io 事件侦听器分成不同的模块吗? [英] Can I separate socket.io event listeners into different modules?

查看:16
本文介绍了我可以将 socket.io 事件侦听器分成不同的模块吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理超过 15 个不同的套接字事件,我想在与这些事件相关的模块中管理某些 socket.io 事件.

I'm handling over 15 different socket events, I'd like to manage certain socket.io events within the modules that are related to those events.

例如,我想让一个名为 login.js 的文件处理 login 套接字事件,一个名为 register.js 的文件处理注册套接字事件.

For example, I'd like to have a file named login.js handle the login socket event, and a file named register.js handle the registration socket event.

index.js:

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

    console.log("Client connected to socket!");

    client.on("login", function (data) {

        validate(data){

            socket.sockets.emit("login_success", data);

        }

    });

    client.on("register", function (data) {

        register(data){

            socket.sockets.emit("register_success", data);

        }

    });

});

有没有一种方法可以将 client.on("register", function (data) { ... 放在一个文件中并将 client.on("login", function(data) { ... 在另一个?

Is there a way that I can put client.on("register", function (data) { ... in one file and client.on("login", function (data) { ... in another?

推荐答案

我通常将各种与客户端相关的功能(我通常称它们为处理程序)拆分为单独的模块,然后 require 并在任何情况下使用它们文件创建 socket.io 连接.

I usually split various client related functionality (I usually call them handlers) into individual modules, and then require and use them in whatever file creates the socket.io connection.

这是一个示例模块,它导出一个期望通过 socket.io 客户端的函数:

Here is an example module, that exports a function which expects to be passed a socket.io client:

/* register-handler.js */
module.exports = function (client) {
  // registration related behaviour goes here...
  client.on('register', function (data) {
    // do stuff
  });
};

由创建新套接字的文件使用,侦听连接,并将它们传递给处理程序,然后处理程序侦听客户端上的事件.

Which is consumed by a file that creates a new socket, listens for connections, and passes them to the handler, which then listens to events on the client.

/*  main.js */
// require your handlers
var handleRegister = require('./register-handler');

// .. set up socket.io

socket.on('connection', function (client) {
  // register handlers
  handleRegister(client);
});

这篇关于我可以将 socket.io 事件侦听器分成不同的模块吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆