3

重复的问题,但我没有找到完美的答案作为解决方案。请帮我解决这个问题。

我的 App.js

   var routes = require('./routes/index');
   var users = require('./routes/users');
   var media = require('./routes/media');
   var widget = require('./routes/widget');
   var display = require('./routes/displays');
   var device = require('./routes/deviceinfo');

   app.use('/', routes);
   app.use('/display', display);


   var server = http.createServer(app);
   var io = require('socket.io')(server);
   io.set('transports', ['polling', 'websocket']);

显示路线:“routes/display.js”

我有插入显示器的代码,一旦创建了显示器,就会向设备列表发出一个事件。

发射应该需要写在保存成功回调方法中。

      var express = require('express');
      var router = express.Router(); 
      router.post('/save', action_save_displays);
      function action_save_displays(req, res){
        display.save(req,body , function(err , display){
               if(!err){
                res.json(display);
                 //io.sockets.emit("displaycreated", display);
              }
        })
      }
       module.exports = routes;

如何在 routes/display.js 文件中传递 io.sockets.emit。非常感谢您的指导。如何将套接字对象发送到路由以启用发出事件。

4

1 回答 1

1

您可以稍微交换一下需求,然后将 socket.io 传递给 display.js 文件

var routes  = require('./routes/index');
var users   = require('./routes/users');
var media   = require('./routes/media');
var widget  = require('./routes/widget');

var server  = http.createServer(app);
var io      = require('socket.io')(server);
var display = require('./routes/displays')(io); // here

var device  = require('./routes/deviceinfo');

app.use('/', routes);
app.use('/display', display);

io.set('transports', ['polling', 'websocket']);

并将其放入display.js文件中

 var express = require('express');
 var router = express.Router(); 

 module.exports = function(io) {

     router.post('/save', function(req, res) {
         display.save(req.body , function(err, display){
             if(!err){
                 res.json(display);
                 io.sockets.emit("displaycreated", display);
              }
         });
     });

    return router;
}
于 2016-01-10T19:07:02.757 回答