Node.js 路由中绑定的事件
我正在使用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 });
});
I'm using expressjs along with nowjs, I'm binding some events to the now object right inside the route when it's being accessed. This isn't very clean, and I have the feeling everything the root is accessed the events are executed.
I'm not sure how, but I wonder if I could move this elsewhere?
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 });
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以将房间代码分离到另一个模块中,甚至可能应用诸如 MVC 到您的应用程序。
我对 Now.js 不是很熟悉,但你明白了——但是代码不涉及另一个模块、另一个文件中的 HTTP 堆栈,并且需要它并在必要时使用它。
You could separate the room code out into another module, perhaps even applying a pattern such as MVC to your app.
I'm not super familiar with Now.js, but you get the idea--but the code that doesn't concern the HTTP stack in another module, in another file, and require it and use it when necessary.