it is a simple socket app using event base pattern
const invitation = require('./invitation');
module.exports = function(io){
io.on('connection', (socket)=>{
var prepareGame = new PrepareGame(socket)
socket.on("sendInvitation",(data, ack)=>{
prepareGame.sendInvitation(data,ack)
});
});
}
and in prepareGame.js
const events = require('events');
const util = require('util');
class PrepareGame extends events {
constructor(socket) {
super();
this.user = socket.user
var self = this
draftInvitation(data){
this.newInvitation = {
from_user: self.user.id,
to_user: data.to_user,
message:data.message,
created_at:moment().unix(),
}
return this
};
self.on("toSocket", (eventName, clientId, data) => {
console.log(` ===>>>> sending to listener ${eventName}`, clientId);
var client = users[clientId]
if(client)
client.emit(eventName, data)
});
}
// public function
sendInvitation(data, ack) {
// console.log(this);
var self = this
data.message = 'New Invitation'
draftInvitation(data)
.emit("toSocket", "getInvitation", data.to_user, self.newInvitation)
setTimeout(()=>{
data.message = 'Invitation timeout'
draftInvitation(data)
.emit("toSocket", "getInvitation", self.user.id, self.newInvitation)
}, 15000)
if(typeof ack == 'function')
ack({
status:200,
message: "invitation sent",
})
}
}
util.inherits(PrepareGame, events.EventEmitter )
module.exports = PrepareGame
code is sum of different design pattern. it's working fine but I've some queries
- io.connection called once to connect to socket and prepareGame instance created. considering two instance for two user then how sendInvitation automatically bound correct instance when calling
- what happen with new prepareGame instance when socket disconnect ?
- i want to remove
(data, ack)=>{ }
encloser from socket.on mean it should socket.on ("sendInvitation",prepareGame.sendInvitation) then how to manage this reference in sendInvitation function
Aucun commentaire:
Enregistrer un commentaire