我有一个包装类,用于管理聊天的单个连接。
当首先收到一条消息ConnectionManager
时,将其作为包装器处理,然后回调到类外部。有什么解决办法吗?
我将单例模式用于连接管理器。
let _instance = null;
class ConnectionManager{
static _hubConnection;
static _proxy;
constructor(hubUrl) {
this._hubConnection = signalr.hubConnection(hubUrl);
this._hubConnection.logging = true;
}
static getInstance(){
if(_instance == null)
_instance = new ConnectionManager(GLOBALS.HUB_URL);
return _instance;
}
createHubProxy(){
this._proxy = this._hubConnection.createHubProxy('Hub');
this._proxy.on('addNewMessage', (message, fileUrl) => {
console.log(message.Body);
if(onReceivedNewMessage)// ---> Where is right place to define?
onReceivedNewMessage(message);
});
}
getHubConnection(){
if(this._hubConnection)
return this._hubConnection;
return null;
}
getHubProxy(){
if(this._proxy)
return this._proxy;
return null;
}
}
module.exports = ConnectionManager;
然后使用类的外侧:
ConnectionManager.getInstance().onReceivedNewMessage( message => {
console.log(message);
});
预先感谢
答案 0 :(得分:0)
let _instance = null;
class ConnectionManager{
static _hubConnection;
static _proxy;
constructor(hubUrl) {
this._hubConnection = signalr.hubConnection(hubUrl);
this._hubConnection.logging = true;
this.createHubProxy();
}
static getInstance(){
if(_instance == null)
_instance = new ConnectionManager(GLOBALS.HUB_URL);
return _instance;
}
onReceiveMessage(callback) {
if(this._proxy) {
this._proxy.on('addNewMessage', callback);
}
}
createHubProxy(){
this._proxy = this._hubConnection.createHubProxy('Hub');
}
getHubConnection(){
if(this._hubConnection)
return this._hubConnection;
return null;
}
getHubProxy(){
if(this._proxy)
return this._proxy;
return null;
}
}
module.exports = ConnectionManager;