简体   繁体   中英

Easily create multiple socket.io events in node.js

Just a quick question around optimisation and DRY. I have my node server and everything works as it should, but I want to know how to clean up for future devs. I have a set of events being assigned like so:

var debug = true;    
io.sockets.on('connection', function (socket) {
    console.log('User connected!');

    socket.on('event-one', function (data) {
        if(debug) { console.log('Event 1!'); }

        socket.broadcast.emit('event-one', data);
    });

    socket.on('event-two', function (data) {
        if(debug) { console.log('Event 2!'); }

        socket.broadcast.emit('event-two', data);
    });

    socket.on('event-three', function (data) {
        if(debug) { console.log('Event 3!'); }

        socket.broadcast.emit('event-three', data);
    });

});

As you can see I'm repeating the socket.on() method. Is there a more efficient way of writing this? I tried a simple array with a for loop but the events stopped working.

Any input would be appreciated. Thanks.

Not sure why your loop didn't work, this works just fine:

var debug  = true;
var events = [ 'event-one', 'event-two', 'event-three' ];

io.sockets.on('connection', function (socket) {  
  events.forEach(function(ev) {
    socket.on(ev, function(data) {
      if (debug) {
        console.log('got event:', ev);
      }
      socket.broadcast.emit(ev, data);
    });
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM