【问题标题】:Is it right that Strophe.addHandler reads only first node from response?Strophe.addHandler 仅从响应中读取第一个节点是否正确?
【发布时间】:2011-02-24 03:31:51
【问题描述】:

我开始学习 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>

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

【问题讨论】:

    标签: javascript xmpp strophe


    【解决方案1】:

    似乎是当调用函数 addHandler 时,堆栈(包含要调用的所有处理程序的数组)在处理程序执行时被清空。所以当匹配handler条件的节点被调用时,堆栈被清空,然后就找不到其他节点了,所以你必须重新设置handler,或者像这样添加你希望调用的handler:

     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;
     }
    

    【讨论】:

      【解决方案2】:

      markcial 的回答是对的。

      在处理函数中返回真,所以 Strophe 不会删除处理函数。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-21
        • 1970-01-01
        • 1970-01-01
        • 2016-08-17
        • 2017-05-19
        • 1970-01-01
        相关资源
        最近更新 更多