Pavel Evsegneev
Pavel Evsegneev

Reputation: 105

Socket.io dynamic "on" binding

I have this code:

var action = "getPost";

clients[socket.id].on(action, function(data) {
            var message = {
                sender : "",
                receiver : "moderation",
                m : {action : action, data: data, socket: socket.id}
            }
            console.log(message);
            console.log("Sockets executing: ", action);
            //process.send(message);
        });

action = "canIGetHoldedPost";

clients[socket.id].on(action, function(data) {
            var message = {
                sender : "",
                receiver : "moderation",
                m : {action : action, data: data, socket: socket.id}
            }
            console.log(message);
            console.log("Sockets executing: ", action);
            //process.send(message);
        });

My problem: when I emits one of this functions, it executes with last action value("canIGetHoldedPost") in the body (m : {action : "canIGetHoldedPost"). How can I bind this functions to get expected result?

I can't just write needed action in the body, because it will be a loop with many events, not only two that I wrote here.

Upvotes: 0

Views: 137

Answers (1)

Salman
Salman

Reputation: 9447

This is the use where you need closure, the reason you're not getting the expected value is that by the time callback gets called, the value of action gets replaced.

You could probably make a function that binds the event. This way the value of action will be preserved till the callback gets executed.

var action = "getPost";
bind(action);

action = "canIGetHoldedPost";
bind(action);

function bind(ac) {
    var action = ac;

    clients[socket.id].on(action, function(data) {
        var message = {
                sender : "",
                receiver : "moderation",
                m : {action : action, data: data, socket: socket.id}
        }
        console.log(message);
        console.log("Sockets executing: ", action);
        //process.send(message);
    });
}

Upvotes: 2

Related Questions