Strophe.addHandler只读取响应中的第一个节点,这是正确的吗?

5
我是一名有用的助手,可以帮您进行文本翻译。以下是需要翻译的内容:

我开始学习 strophe 库的使用,当我使用 addHandler 解析响应时,似乎只读取 xml 响应的第一个节点,因此当我收到这样的 xml 时:

<body xmlns='http://jabber.org/protocol/httpbind'>
 <presence xmlns='jabber:client' from='test2@localhost' to='test2@localhost' type='avaliable' id='5593:sendIQ'>
  <status/>
 </presence>
 <presence xmlns='jabber:client' from='test@localhost' to='test2@localhost' xml:lang='en'>
  <status />     
 </presence>
 <iq xmlns='jabber:client' from='test2@localhost' to='test2@localhost' type='result'>
  <query xmlns='jabber:iq:roster'>
   <item subscription='both' name='test' jid='test@localhost'>
    <group>test group</group>
   </item>
  </query>
 </iq>
</body>

使用testHandler处理程序:

connection.addHandler(testHandler,null,"presence");
function testHandler(stanza){
  console.log(stanza);
}

它只记录:

<presence xmlns='jabber:client' from='test2@localhost' to='test2@localhost' type='avaliable' id='5593:sendIQ'>
 <status/>
</presence>

我错过了什么?这是正确的行为吗?我应该添加更多的处理程序来获取其他的信息吗? 提前感谢。
2个回答

11
似乎当调用addHandler函数时,堆栈(包含所有要调用的处理程序的数组)在执行处理程序时被清空。因此,当调用与处理程序条件匹配的节点时,堆栈被清除,然后其他节点将无法找到,因此您必须重新设置处理程序或像这样添加您期望被调用的处理程序:
 connection.addHandler(testHandler,null,"presence");
 connection.addHandler(testHandler,null,"presence");
 connection.addHandler(testHandler,null,"presence");

或:

 connection.addHandler(testHandler,null,"presence");
 function testHandler(stanza){
    console.log(stanza);
    connection.addHandler(testHandler,null,"presence");
 }
可能不是最好的解决方案,但在有更好的解决方案出现之前我会使用它。无论如何,我发布这个解决方法是为了给出我正在处理的代码流程的提示。
编辑
在阅读 http://code.stanziq.com/strophe/strophejs/doc/1.0.1/files/core-js.html#Strophe.Connection.addHandler中的文档后,我发现以下内容:
如果要再次调用处理程序,则处理程序应返回 true;返回 false 将在返回后删除处理程序。
因此,只需添加一行即可解决问题:
 connection.addHandler(testHandler,null,"presence");
 function testHandler(stanza){
    console.log(stanza);
    return true;
 }

4

markcial的回答是正确的。

在处理函数中返回true,这样Strophe就不会删除处理程序。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接