Vâng, bạn có thể đạt được những theo những cách khác nhau, như:
- đối tượng thiết lập để không gian tên toàn cầu. (thay đổi chăm sóc nhu cầu toàn cầu)
- Sử dụng module.exports và yêu cầu đối tượng trong các tệp khác. (có thể dẫn đến các vấn đề phụ thuộc vòng tròn nếu không được thực hiện đúng cách)
- chuyển trường hợp làm đối số cho bộ điều khiển, trong khi yêu cầu chúng trong các tuyến.
myModule.jsMô-đun đó cho thấy chức năng của thư viện của bạn Socket.IO
const sio = require('socket.io');
module.exports = function(server) {
const io = sio(server);
return {
register: function(namespace) {
let nsp = io.of(namespace);
nsp.on('connect', function(socket) {
// ...
}
}
}
}
dòng 1: thiết lập các mô-đun trong không gian tên toàn cầu.
app.js
var app = require('express').createServer();
var io = require('./myModule')(app);
global._io = io;
app.listen(80)
controller.js
module.exports = function(io){
var that={};
/*
* Private local variable
* made const so that
* one does not alter it by mistake
* later on.
*/
const _io = global._io;
that.myAction = function(req,res){
_io.register('newRoom');
res.send('Done');
}
return that;
}
Dòng 2: qua mô-đun như các đối số.
app.js
var app = require('express').createServer();
var io = require('./myModule')(app);
require(./router.js)(app,io);
app.listen(80);
router.js
/*
* Contains the routing logic
*/
module.exports = function (app,io) {
//passing while creating the instance of controller for the first time.
var controller = require("./controller")(io);
app.get('/test/about',controller.myAction);
};
controller.js
module.exports = function(io){
var that={};
const _io = io;
that.myAction = function(req,res){
_io.register('newsRoom');
res.send('Done');
}
// everything attached to that will be exposed
// more like making public member functions and properties.
return that;
}
Dòng 3: Thiết io đến toàn cầu. Vì vậy, không cần phải vượt qua máy chủ mỗi lần.
app.js
var app = require('express').createServer();
require('./myModule')(app);
require(./router.js)(app);
app.listen(80);
controller.js
// no need to pass the server as io is already initialized
const _io = require('./myModule')();
module.exports = function(io){
var that={};
that.myAction = function(req,res){
_io.register('newsRoom');
res.send('Done');
}
return that;
}
myModule.js
module.exports = function(server) {
const _io = global._io || require('socket.io')(server);
if(global._io === undefined){
//initializing io for future use
global._io = _io;
}
return {
register: function(namespace) {
let nsp = _io.of(namespace);
nsp.on('connect', function(socket) {
// ...
}
}
}
}
Có lẽ, cách sạch nhất là truyền là đối số cho các bộ điều khiển, trong khi yêu cầu chúng trong các tuyến. Mặc dù dòng chảy thứ 3 có vẻ đầy hứa hẹn nhưng người ta phải cẩn thận trong khi thay đổi không gian tên chung.
Tôi nghĩ bạn nên giữ cho nó đơn giản và hiển thị 'io' từ tập lệnh bắt đầu của máy chủ (có thể là tệp app.js/web.js trong dự án của bạn) và sử dụng lại ví dụ đó trong mô-đun của bạn. – gevorg