file2.js中有一个函数可以创建一些数据。此数据应转到file1.js,并应从那里发送到客户端。我该怎么办?
app.js:
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var file1 = require('./file1')(io);
file1.js:
var file2 = require('./file2');
//This is how it usually works if I want to interact with a client:
module.exports = function(io) {
io.on('connection', function (socket) {
socket.on('channel_x', function (data, callback) {});
});
}
//What if I want to send (emit) data which comes from another file to the client?
exports.functionInFile1 = function(exampleDataFromFile2) {
//How to send "exampleDataFromFile2" to client from here?
}
file2.js:
var file1 = require('./file1');
function functionInFile2() {
//do something
var exampleData = {some: "data"};
file1.functionInFile1(exampleData);
}
functionInFile2();
答案 0 :(得分:0)
为什么不像io
一样向file2
提供file1
实例,然后再从那里本身向客户端发送数据。
file2.js
function functionInFile2(io) {
//do something
var exampleData = { some: "data" };
io.emit('message', exampleData);
}
module.exports = functionInFile2;
file1.js
var functionFile2 = require('./file2');
module.exports = function(io) {
io.on('connection', function(socket) {
socket.on('channel_x', function(data, callback) { });
});
functionFile2(io);
}