B
B
Ben L2018-12-16 12:15:36
JavaScript
Ben L, 2018-12-16 12:15:36

How to pass io.to('...') as function parameter?

Hello
Here is a sample code:
On the server:

...
function start(socket) {
    setInterval(() => {
        socket.emit('update', Date.now());
    }, 2e3);
}

function main(io) {
    let connectons = [];
    let index = 0;
    io.on('connection', (socket) => {
        socket.on('start', () => {
            const { id }= socket;
            if (!connectons[id]) {
                connectons[id] = true;
                const group = `gr-${index}`;
                socket.join(group);
                ++index;
                start(io.to(group));
                // setInterval(() => {
                //    socket.emit('update', Date.now());
                // }, 1e3);
            }
        });
    });
}

main(io);


on the client:
socket.on('update', (time) => {
    console.log(time);
});
$('#start').click(() => {
    socket.emit('start');
});


If you click on the buttons on 1 of the clients, we see logs for all clients in the console. Why is that? I'm waiting for the logs only on the client on which I clicked the button.
If you do not call start() but immediately setInterval(() => { .... then everything works as I expect
. Help me to help why this is so.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
JorJeG, 2018-12-16
@JorJeG

Here you lose this, as in this example

var name = 'window';
var obj = {
  name: 'obj',
  show: function() {
    console.log(this.name)
  }
};

var func = obj.show;
func();  // Твой случай

obj.show();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question