2011-12-31 6 views
0

私はnowjsと一緒にexpressjsを使用していますが、私はいくつかのイベントを現在のオブジェクトにバインドしています。これはあまりきれいではなく、イベントが実行されたときにルートにアクセスするすべてのことを感じています。イベント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()イベントが呼び出されることを心配していました。これは今のところできます。ありがとう。 –

関連する問題