代码之家  ›  专栏  ›  技术社区  ›  markcial

strophe.addhandler只从响应中读取第一个节点是正确的吗?

  •  5
  • markcial  · 技术社区  · 16 年前

    我开始学习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 回复  |  直到 15 年前
        1
  •  11
  •   markcial    16 年前

    似乎在调用函数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;
     }
    
        2
  •  4
  •   bitshine    15 年前

    马卡利的回答是对的。

    在handler函数中返回true,因此strophe不会移除该处理程序。