cc young
cc young

Reputation: 20213

in node.js using socket.io, how to add to socket listener dynamically?

if have standard socket.io setup:

var app = require('http').createServer().listen(80,'127.0.5.12'),
io = require('socket.io').listen(app);

session = require('./local_modules/session.js');

// creating a new websocket to keep the content updated without any AJAX request
io.sockets.on('connection', function(socket) {

  // session, login, logout
  socket.on( 'session', session.session.bind(socket) );
  socket.on( 'login', session.login.bind(socket) );
  socket.on( 'logout', session.logout.bind(socket) );

  // what to add new listener here!
});

later in the program, once it knows what it wants to do, it wishes to add new functionality to the socket listener. for example, in the middle of 'session' might wish to add 'something-new':

exports.session = function( sid) {
  var socket = this;
  ...
  // everything cool, now want to add 'something-now' to socket
  // do I simply - will something simple as this work?
  socket.on( 'something-new', session.something_new.bind(socket) );
}

exports.something_new = function( arg ) {
}

is this correct - it just seems wrong?

Upvotes: 1

Views: 2043

Answers (1)

gherkins
gherkins

Reputation: 14983

If you just want to call 'whatever.func()' on the socket event 'something-new'

socket.on('something-new', whatever.func(data) );

or

socket.on('something-new', function(data){
  whatever.func(data);
  whatelse.func(data.someproperty);
});

should work, while 'data' is the first argument passed, when emitting 'something-new'.

Upvotes: 2

Related Questions