对于我的REST api,我为每条路线创建了一个文件。
app.get('/api/user', routes.user.index);
app.get('/api/user/login', routes.user.login);
等等
现在我将socket.io引入后端,似乎我只能为所有套接字事件调用一个函数。
var socket = require('./socket/stuff.js');
io.sockets.on('connection', function(sock){
socket.stuff(sock, io);
});
我该如何分手呢? ./socket/stuff.js
文件(导出 stuff
)。分成单独的文件。我想最终用套接字替换我的REST api,但我不希望一切都在一个文件中。
我想我会:
./socket/chat.js
./socket/user.js
等等
要在不同的文件中组织事件处理程序,可以使用如下结构:
./main.js
var io = require('socket.io');
var Chat = require('./EventHandlers/Chat');
var User = require('./EventHandlers/User');
var app = {
allSockets: []
};
io.sockets.on('connection', function (socket) {
// Create event handlers for this socket
var eventHandlers = {
chat: new Chat(app, socket),
user: new User(app, socket)
};
// Bind events to handlers
for (var category in eventHandlers) {
var handler = eventHandlers[category].handler;
for (var event in handler) {
socket.on(event, handler[event]);
}
}
// Keep track of the socket
app.allSockets.push(socket);
});
./EventHandlers/Chat.js
var Chat = function (app, socket) {
this.app = app;
this.socket = socket;
// Expose handler methods for events
this.handler = {
message: message.bind(this) // use the bind function to access this.app
ping: ping.bind(this) // and this.socket in events
};
}
// Events
function message(text) {
// Broadcast message to all sockets
this.app.allSockets.emit('message', text);
});
function ping() {
// Reply to sender
this.socket.emit('message', 'PONG!');
});
module.exports = Chat;
要在不同的文件中组织事件处理程序,可以使用如下结构:
./main.js
var io = require('socket.io');
var Chat = require('./EventHandlers/Chat');
var User = require('./EventHandlers/User');
var app = {
allSockets: []
};
io.sockets.on('connection', function (socket) {
// Create event handlers for this socket
var eventHandlers = {
chat: new Chat(app, socket),
user: new User(app, socket)
};
// Bind events to handlers
for (var category in eventHandlers) {
var handler = eventHandlers[category].handler;
for (var event in handler) {
socket.on(event, handler[event]);
}
}
// Keep track of the socket
app.allSockets.push(socket);
});
./EventHandlers/Chat.js
var Chat = function (app, socket) {
this.app = app;
this.socket = socket;
// Expose handler methods for events
this.handler = {
message: message.bind(this) // use the bind function to access this.app
ping: ping.bind(this) // and this.socket in events
};
}
// Events
function message(text) {
// Broadcast message to all sockets
this.app.allSockets.emit('message', text);
});
function ping() {
// Reply to sender
this.socket.emit('message', 'PONG!');
});
module.exports = Chat;