Su4p
Su4p

Reputation: 865

-beginner- trouble with multiple users and variables

I'm trying to build a module that handle a form like a powerpoint (slide by slide) I described my form in a Json file.

When a user connects I read the json and serve him the first question. When the user click on the next button I iterate on my counter and serve him the second question.

For one user it works great.

But I came to realize that when two user are connected they share the same counter.

This is a problem.

In order to fix this issue : I could handle an array with session ID to identify each user. But I'm pretty sure there is a better way to do so.

Obviously I'm a beginner with node.js

What I do in app.js

io.sockets.on('connection', function(socket) {
    var form = require('./controllers/form');
    form.init();

    socket.on('next', function(data) {
        socket.emit('next', form.next());
    });
});

A part of my form.js for you to better understand my problem :

var formController = {
    'form': [],
    'lookup_part_iterator': 0,
    'lookup_diapo': {},
    'lookup_diapo_iterator': 0,
    'init': function() {//stuff},
    'next': function() {//stuff},
    'end': function() {//stuff},
    'get_next_slide': function() {//stuff},
    'iterate_slide': function() {//stuff},
    'iterate_part': function() {//stuff},

}

Upvotes: 0

Views: 55

Answers (2)

Su4p
Su4p

Reputation: 865

I manage to do it but I'm not satisfied please if someone know a better way to do this explain it. In app.js :

io.sockets.on('connection', function(socket) {

var form = require('./controlers/form');
form.init();
var form_copy = _.extend({},form);
    socket.set( socket.id, form_copy, function() {
    console.log("form setted");
    socket.on('next', function(data) {
        console.log("next");
        socket.get( socket.id,function(error,form_socket){
            //I will handle the error ty Tim
            console.log("form getted"+error);
             console.log(form_socket);
            socket.emit('next', form_socket.next());
        });

    });
});


});

@Tim Brown : in my case socket.set alone is not working because it's passing a reference so I end up dealing with the same issue.

My workaround is to make a copy of the form object before passing it to socket.set. But as I said I'm not satisfied even thow it's working. Maybe It's the best way tell me what you think in the comments.

Upvotes: 0

Tim Brown
Tim Brown

Reputation: 3241

Use socket.set(key, value, cb) and socket.get(key, function(err, value){...})

UPDATE: Added the whole thing in context.

io.sockets.on('connection', function(socket) {
    var form = require('./controllers/form');
    form.init();
    socket.set("form", form)

    socket.on('next', function() {
        socket.get('form', function(err, form) {
            // HANDLE THE ERR, usually just something like if(err){ return }
            socket.emit('next', form.next());
        });
    });
});

Upvotes: 1

Related Questions