我有一个像这样的app.js文件:
...
var socket = require('./app/sockets')(io)
var routes = require('./app/routes')(server, socket)
...
sockets.js看起来像这样:
exports = module.exports = function(io) {
return {
emit: function() {
io.emit('hi', "Some stuff")
}
}
}
routes.j文件如下所示:
exports = module.exports = function(app, io) {
...
var user = require('./controllers/user')(io)
app.get({ path: '/users/:id', version: '1.0' }, user.getUserById);
...
}
最后,我的user.js文件如下所示:
exports = module.exports = function(io) {
return {
...
getPersonById: function(req, res, next) {
....
io.emit("Hello")
...
},
....
}
}
有没有更好的方法来组织这个?我觉得我正在通过4个不同的文件来线程化我的io实例。我只想要一个单例实例,我可以从我的控制器中发出事件。
答案 0 :(得分:1)
我,在express.io中使用类似的东西:
app.js
var router = require('./routes/router'),
express = require('express.io'),
app = new express();
app.http().io();
app.use(app.router);
app = router.index(app);
app.listen(3000);
./路由/ router.js
exports.index = function(app){
var IndexIo = require(__maindir + '/routes/io/IndexIo');
app.io.route('page/action', IndexIo.action);
app.io.route('page/action2', IndexIo.action2);
return app;
};
/routes/io/IndexIo.js
exports.action = function(req){
doSomething();
req.io.emit('doSomething', {});
}
exports.action2 = function(req){
doSomething();
req.io.emit('doSomething', {});
}