0

When we are having and ajax call in jquery we can write it this way:

$.ajax({
    url: 'http://localhost/url',
    type: 'GET',
    dataType: "json",          
    data: {name : "data"},
    beforeSend : function(){
    ...
    },
    success:function(data)
    {
    ...
    },  
    error : function(){
    ...
    }
}
});

Is this declaration template/style can also be applied to socket event handling in Socket.IO?

Can we do something like:

var socket = io.connect( );

socket.on({
    'connect' : function(){
     ...
     },
    'error' : function(){
    ...
    },
    'my custom event' : function(){
    ...
    }
}

)

Thanks!

leonard.javiniar
  • 539
  • 8
  • 25

1 Answers1

0

In socket.io docs they show you can do it using the chain of calls:

socket.on(...)
      .on(...)
      .on(...)

If you really don't want it, you can simply write a module wrapping it:

yourNameSpace.Socket = (function(){
    var socket = null;

    this.config = function(){
        socket = io.connect("...");
    };

    this.on = function(events){
        for(var ev in events){
            if(typeof events == 'object' && events.hasOwnProperty(ev)){
                socket.on(ev, events[ev]);
            }
        }
    };

    this.getSocket = function(){
        return socket;
    };

    return this;
})();

Note that is not a constructor, but a module. It behavior is a singleton, so if you want more than one socket connection, simply convert it into a constructor. :)

Rubens Pinheiro
  • 490
  • 5
  • 11