2011-12-31 42 views
0

我使用expressjs与nowjs一起,当它被访问时,我将一些事件绑定到路由中的now对象。这不是很干净,而且我感觉到事件执行时访问根的所有内容。绑定在路由中的事件Node.js

我不知道如何,但我不知道我是否可以移动这个地方?

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 }); 
}); 

回答

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堆叠在另一个模块,在另一个文件中的代码,并要求它,使用它必要时。

+0

是的,我明白了。我更关心在每个页面访问时调用.on()事件。这会做现在。谢谢。 – 2011-12-31 20:53:45