【问题标题】:Event binded in route Node.js路由 Node.js 中绑定的事件
【发布时间】:2012-01-30 22:59:09
【问题描述】:

我将 expressjs 与 nowjs 一起使用,当访问路由时,我将一些事件绑定到路由内的 now 对象。这不是很干净,我感觉根目录访问的所有内容都执行了事件。

我不知道怎么做,但我想知道我是否可以把它移到别处?

app.get('/room/:name', function(req, res)
{
  //Should this code be moved elsewhere?... how?
  nowjs.on('connect', function()
  {
    this.now.room = req.params.name;
    nowjs.getGroup(this.now.room).addUser(this.user.clientId);
    console.log("Joined: " + this.now.name);
  });

  everyone.now.distributeMessage = function(message){
    nowjs.getGroup(this.now.room).now.receiveMessage(this.now.name, message);
  };

  res.render('room', { user : user });
});

【问题讨论】:

    标签: javascript node.js express nowjs-sockets


    【解决方案1】:

    您可以将房间代码分离到另一个模块中,甚至可以将MVC 之类的模式应用到您的应用中。

    var Room = require('./models/room');
    
    ...
    
    app.get('/room/:name', function(req, res) {
      Room.initialize(params.name);
      res.render('room', {user: user});
    });
    
    // models/room.js
    
    Room = {
      initialize: function(name) {
        nowjs.on('connect', function() {
          this.now.room = name;
          nowjs.getGroup(this.now.room).addUser(this.user.clientId);
          console.log("Joined: " + this.now.name);
        });
    
        everyone.now.distributeMessage = function(message){
          nowjs.getGroup(this.now.room).now.receiveMessage(this.now.name, message);
        };
      }
    };
    
    module.exports = Room; // makes `require('this_file')` return Room
    

    我对 Now.js 不是很熟悉,但你明白了——但代码与另一个模块、另一个文件中的 HTTP 堆栈无关,需要它并在必要时使用它。

    【讨论】:

    • 是的,我明白了。我更关心在每次访问页面时都会调用 .on() 事件。现在就可以了。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2011-05-17
    • 2016-06-30
    • 1970-01-01
    • 2013-02-11
    • 1970-01-01
    • 2016-07-25
    • 2017-03-15
    • 1970-01-01
    相关资源
    最近更新 更多