如果具有标准的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 ) {
}


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

最佳答案

如果您只想在套接字事件“新事物”上调用“ whatever.func()”

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


要么

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


当发出“新事物”时,“数据”是传递的第一个参数,它应该起作用。

10-07 19:50
查看更多