我正在开发一个通用库,用于通过 BOSH 服务与 xmpp 用户通信。我使用 Strophe.js
我不明白为什么在类 BoshCommunicator 方法 onConnect 我有一个 Strophe 对象,但没有 BoshCommunicator 预期。
当我 console.log(this) 我得到 Object { service="http://myboshim/http-bind", jid="aivaras37@myboshim/29785298701381498988721337", rid=4092107607, more...}
此外,在建立连接之前,我为 BoshCommunicator 类设置了侦听器属性。当我 console.log(this.listener) 我得到未定义的时候,但是如果我在 connect() 方法中使用 console.log(this.listener) 我会得到监听器对象的预期转储。你能解释一下如何在 BoshCommunicator.prototype.onConnect() 中初始化 BoshCommunicator 吗?还请解释为什么我丢失了我的对象并获得了 Strophe。
这是我使用的特定代码:
function BoshCommunicator(boshUri, host)
{
this.connection = null;
this.boshUri = null;
this.host = null;
this.listener = null;
this.setBoshUri(boshUri);
this.setHost(host);
}
BoshCommunicator.prototype.setBoshUri = function(boshUri)
{
this.boshUri = boshUri;
};
BoshCommunicator.prototype.setHost = function(host)
{
this.host = host;
};
BoshCommunicator.prototype.setListener = function(listener)
{
this.listener = listener;
this.listener.setListenHost(this.host);
};
BoshCommunicator.prototype.connect = function(jid, jpass)
{
this.connection = new Strophe.Connection(this.boshUri);
this.connection.connect(jid, jpass, this.onConnect);
};
BoshCommunicator.prototype.onConnect = function(status)
{
if (status === Strophe.Status.CONNECTED) {
console.log("Send me messages!");
console.log(this); // dumps strophe object. Paste from console: Object { service="http://myboshim/http-bind", jid="aivaras37@myboshim/29785298701381498988721337", rid=4092107607, more...}
console.log(this.listener); // undefined - how come?
this.connection.addHandler(this.listener.onReceivedMessage, null, 'message', null, null, null);
this.connection.send($pres().tree());
}
};
function MessageListener()
{
this.host = null;
}
MessageListener.prototype.setListenHost = function(host)
{
this.host = host;
};
function ReceivedMessageNotify()
{
MessageListener.call(this);
}
ReceivedMessageNotify.prototype = new MessageListener();
ReceivedMessageNotify.prototype.constructor = ReceivedMessageNotify;
ReceivedMessageNotify.prototype.onReceivedMessage = function(message)
{
console.log(message);
var elems = message.getElementsByTagName('body');
var body = elems[0];
if (Strophe.getText(body).length > 0) {
this.sendNewMessageNotify(message.getAttribute('from'), Strophe.getText(body));
}
return true;
};
ReceivedMessageNotify.prototype.sendNewMessageNotify = function(sender, messageBody)
{
alert("New message: " + sender + " wrote: " + messageBody);
};
$(document).ready(function() {
var communicator = new BoshCommunicator('http://myboshim/http-bind', 'myboshim');
communicator.setListener(new ReceivedMessageNotify());
communicator.connect('jabberId', 'accPasswd');
});