0

我将 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 });
});
4

1 回答 1

0

您可以将房间代码分离到另一个模块中,甚至可以将诸如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 堆栈无关,需要它并在必要时使用它。

于 2011-12-31T06:06:26.900 回答