2011-12-31 39 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