您正在尝试反转控制流程。这样做的方法是让您的控制器实现一个接口(API),您的服务器可以使用该接口将控制权传递给。
一个简单的例子是:
在mycontroller.js
// no require needed here, at least, I don't think so
// Controller agrees to implement the function called "respond"
module.exports.respond = function(socket_io){
// this function expects a socket_io connection as argument
// now we can do whatever we want:
socket_io.on('news',function(newsreel){
// as is proper, protocol logic like
// this belongs in a controller:
socket.broadcast.emit(newsreel);
});
}
现在在server.js
:
var io = require('socket.io').listen(80);
var controller = require('./mycontroller');
io.sockets.on('connection', controller.respond );
这个例子很简单,因为控制器 API 看起来很像 socket.io 回调。但是如果你想将其他参数传递给控制器呢?像io
对象本身还是代表端点的变量?为此,您需要做更多的工作,但这并不多。这与我们经常用来打破或创建闭包的技巧基本相同:函数生成器:
在mycontroller.js
module.exports.respond = function(endpoint,socket){
// this function now expects an endpoint as argument
socket.on('news',function(newsreel){
// as is proper, protocol logic like
// this belongs in a controller:
endpoint.emit(newsreel); // broadcast news to everyone subscribing
// to our endpoint/namespace
});
}
现在在服务器上,我们需要做更多的工作才能通过终点:
var io = require('socket.io').listen(80);
var controller = require('./mycontroller');
var chat = io
.of('/chat')
.on('connection', function (socket) {
controller.respond(chat,socket);
});
请注意,我们直接通过,但我们通过闭包socket
捕获。chat
有了这个,您可以拥有多个端点,每个端点都有自己的控制器:
var io = require('socket.io').listen(80);
var news_controller = require('./controllers/news');
var chat_controller = require('./controllers/chat');
var news = io
.of('/news')
.on('connection', function (socket) {
news_controller.respond(news,socket);
});
var chat = io
.of('/chat')
.on('connection', function (socket) {
chat_controller.respond(chat,socket);
});
实际上,您甚至可以为每个端点使用多个控制器。请记住,控制器除了订阅事件之外什么都不做。正在监听的是服务器:
var io = require('socket.io').listen(80);
var news_controller = require('./controllers/news');
var chat_controller = require('./controllers/chat');
var chat = io
.of('/chat')
.on('connection', function (socket) {
news_controller.respond(chat,socket);
chat_controller.respond(chat,socket);
});
它甚至适用于普通的 socket.io(无端点/命名空间):
var io = require('socket.io').listen(80);
var news_controller = require('./controllers/news');
var chat_controller = require('./controllers/chat');
io.sockets.on('connection', function (socket) {
news_controller.respond(socket);
chat_controller.respond(socket);
});