它是一个使用事件基础模式的简单套接字应用程序
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)
});
});
}
和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
代码是不同设计模式的总和。它工作正常,但我有一些疑问
(data, ack)=>{ }
封闭器
应该socket.on(" sendInvitation",prepareGame.sendInvitation)然后
如何在sendInvitation函数中管理此引用