1

如果有标准socket.io设置:

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!
});

稍后在程序中,一旦它知道它想要做什么,它希望向套接字侦听器添加新功能。例如,在“会话”中间可能希望添加“新事物”:

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 ) {
}

这是正确的 - 它似乎是错误的吗?

4

1 回答 1

2

如果您只想在套接字事件 'something-new' 上调用 'whatever.func()'

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

或者

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

应该可以工作,而 'data' 是传递的第一个参数,当发出 'something-new' 时。

于 2012-07-08T09:59:53.517 回答