1

I need some help with socket.io and bacon.JS:

I have on the client side a socket.IO emit event that sends 2 parameters to the server, as shown below:

$("#btn").asEventStream("click").onValue(function(){
    socket.emit("event", param1, param2);
});

Then on the server side I need to receive these 2 parameters so I can do stuff with them.

Following the example on this answer, I tried doing something like this:

    io.on('connection', function (socket) {
        socket.on('error', function (err) {
            console.log(err);
        });

        Bacon.fromEvent(socket, "event", param1, param2)
            .filter(function(param1, param2){ return true })
            .forEach(function(param1, param2){
                doStuff(param1, param2);
            });
    });

But it didn't work.

Summarizing, I need to receive the event on the server as an EventStream, and use the parameters.

Can anyone help me?

Community
  • 1
  • 1

1 Answers1

2

I solved it!

Turns out you send objects using the bacon.js + socket.io combo.

When you emit a socket.io event with an object as parameter, you can capture this event in an Event Stream, and each event on that stream will actually be the object you sent as parameter.

So what I did was:

//client side
$("#btn").asEventStream("click").onValue(function(){
    var obj = {p1: param1, p2: 'param2'};
    socket.emit("someEvent", obj);
});

//server side
Bacon.fromEvent(socket, "someEvent")
    .onValue(function(data){
        doStuff(data.p1, data.p2);
    });

Or you can also do something with the object and emit a socket event back with the result, like this:

//server side

//doStuff can return anything, it doesn't have to be an object
function doStuff(data){if data.p2 === 'param2' {return true}};

Bacon.fromEvent(socket, "someEvent")
    .map(function (data) { return doStuff(data) })
    .onValue(socket, "emit", "returnEvent");

and then you can capture the returning event on the client side, and each event on this resulting EventStream will be the return of the "doStuff" function:

//client side
Bacon.fromEvent(socket, "returnEvent")
    .onValue(function(data){
        console.log(data);
    });