2014-07-26 63 views
0

我似乎缺乏對如何構造節點模塊的理解。我有以下app.js在node.js中構造模塊和socket.io

var io = require('socket.io')(http); 
io.on('connection', function(socket){ 

    socket.on('disconnect', function(){ 
     console.log('user disconnected'); 
    }); 

    console.log("New user " + socket.id); 
    users.push(socket.id); 
    io.sockets.emit("user_count", users.length); 
}); 

這很好。我可以對來自客戶端的各種消息作出反應,但我也有幾個需要對不同消息作出反應的模塊。比如我cardgame.js模塊應反應:

socket.on("joinTable"... 
socket.on("playCard" 

雖然我chessgame.js應該反應

socket.on("MakeAMove"... 

和我user.js的文件句柄:

socket.on('register' ... 
socket.on('login' ... 

我將如何銜接/構造我的文件來處理這些不同的消息,以便對套接字請求作出反應的文件不會變得太大。

基本上,如果我可以將套接字對象傳遞給這些模塊將會很好。但問題是,直到連接建立,套接字將是未定義的。

此外,如果我將整個io變量傳遞給我的模塊,那麼每個模塊都將有io.on('connection',..)調用。不知道這是甚至可能或希望。

回答

1

你不需要傳遞整個io對象(但你可以,我只是爲了防止我需要它)。只需通過插座上的連接模塊,然後將您的具體on回調模塊

主要

io.on("connection",function(socket){ 
    //... 
    require("../someModule")(socket); 
    require("../smoreModule")(socket); 
}); 

插座

//Convenience methods to setup event callback(s) and 
//prepend socket to the argument list of callback 
function apply(fn,socket,context){ 
    return function(){ 
     Array.prototype.unshift.call(arguments,socket); 
     fn.apply(context,arguments); 
    }; 
} 

//Pass context if you wish the callback to have the context 
//of some object, i.e. use 'this' within the callback 
module.exports.setEvents = function(socket,events,context){ 
    for(var name in events) { 
     socket.on(name,apply(events[name],socket,context)); 
    } 
}; 

someModule

var events = { 
    someAction:function(socket,someData){ 

    }, 
    smoreAction:function(socket,smoreData){ 

    } 
} 

module.exports = function(socket){ 
    //other initialization code 
    //... 

    //setup the socket callbacks for the connected user 
    require("../socket").setEvents(socket,events); 
}; 
+0

這看起來像我想要的。如何處理模塊,但需要多個套接字?我假設先創建對象,然後簡單地使用addSocket函數。 –