2013-12-09 21 views
9

REST api için Her yol için bir dosya oluşturdum.node.js ve socket.io uygulamasında soket yürütme nasıl düzenlenir

app.get('/api/user', routes.user.index); 
app.get('/api/user/login', routes.user.login); 

vs vs

Şimdi arka uca socket.io takdim edeceğim ve ben sadece tüm soket etkinlikler için tek bir işlevi çağırabilir görünüyor.

var socket = require('./socket/stuff.js'); 

io.sockets.on('connection', function(sock){ 
    socket.stuff(sock, io); 
}); 

nasıl (stuff ihraç olan) ./socket/stuff.js dosyasını ayrılmalıyız. Ayrı dosyalar içine. En sonunda REST api'mizi yuvalarla değiştirmek istiyorum, ancak her şeyin tek bir dosyada olmasını istemiyorum.

ben olurdu düşünün:

./socket/chat.js 
./socket/user.js 

vs vs

cevap

13

farklı dosyalarda etkinlik işleyicileri organize etmek için böyle bir yapıyı kullanabilirsiniz:

./main. js

var io = require('socket.io'); 
var Chat = require('./EventHandlers/Chat'); 
var User = require('./EventHandlers/User'); 

var app = { 
    allSockets: [] 
}; 

io.sockets.on('connection', function (socket) { 

    // Create event handlers for this socket 
    var eventHandlers = { 
     chat: new Chat(app, socket), 
     user: new User(app, socket) 
    }; 

    // Bind events to handlers 
    for (var category in eventHandlers) { 
     var handler = eventHandlers[category].handler; 
     for (var event in handler) { 
      socket.on(event, handler[event]); 
     } 
    } 

    // Keep track of the socket 
    app.allSockets.push(socket); 
}); 

./EventHandlers/Chat.js

var Chat = function (app, socket) { 
    this.app = app; 
    this.socket = socket; 

    // Expose handler methods for events 
    this.handler = { 
     message: message.bind(this) // use the bind function to access this.app 
     ping: ping.bind(this) // and this.socket in events 
    }; 
} 

// Events 

function message(text) { 
    // Broadcast message to all sockets 
    this.app.allSockets.emit('message', text); 
}); 

function ping() { 
    // Reply to sender 
    this.socket.emit('message', 'PONG!'); 
}); 

module.exports = Chat; 
+0

Bir örnek soket olay işleyicisi için 'chat.js' nasıl görünür? – chovy

+0

@chovy Güncellenmiş cevabımı –

+0

görüyorum. Ama ben sadece '' ('./ soketler') gerektirir, kayıt (çorap, io) 've' '' ''/chat.js' ve '/ user.js' tarafından dışa aktarılan' register' işlevlerini çağıran bir işlevi vardır. – chovy

İlgili konular