由于app.js通常是应用程序中的主要初始化模块,因此通常会同时初始化Web服务器和socket.io并加载应用程序所需的其他内容。
因此,
io与其他模块共享的一种典型方法是将它们传递给该模块的构造函数中的其他模块。那会像这样工作:
var server = require('http').createServer(app);var io = require('socket.io')(server);// load consumer.js and pass it the socket.io objectrequire('./consumer.js)(io);// other app.js pre follows然后,在consumer.js中:
// define constructor function that gets `io` send to itmodule.exports = function(io) { io.on('connection', function(socket) { socket.on('message', function(message) { logger.log('info',message.value); socket.emit('ditConsumer',message.value); console.log('from console',message.value); }); });};或者,如果您想使用一种
.start()方法来初始化事物,则可以对此进行相同的操作(存在细微差别):
// app.jsvar server = require('http').createServer(app);var io = require('socket.io')(server);// load consumer.js and pass it the socket.io objectvar consumer = require('./consumer.js);consumer.start(io);// other app.js pre follows而Consumer.js中的start方法
// consumer.js// define start method that gets `io` send to itmodule.exports = { start: function(io) { io.on('connection', function(socket) { socket.on('message', function(message) { logger.log('info',message.value); socket.emit('ditConsumer',message.value); console.log('from console',message.value); }); }); };}这就是所谓的资源共享“推送”模块。正在加载的模块通过在构造函数中传递一些共享信息给您。
还有“拉”模型,其中模块本身调用其他模块中的方法来检索共享信息(在这种情况下为
io对象)。
通常,可以使任何一个模型都可以工作,但是鉴于模块的加载方式以及谁拥有所需的信息以及您打算如何在其他情况下重用模块,通常一个或另一个模型会更自然。



