Multiple ScriptEventListeners

    This site uses cookies. By continuing to browse this site, you are agreeing to our Cookie Policy.

    • Multiple ScriptEventListeners

      Hey,

      I have a question regarding the EventManager::AddScriptListener function on page 337 of GCC3;

      the code to check for duplicate eventlisteners:-

      // OK, valid event type. Make sure this isn't a duplicate
      ScriptEventListenerMap::const_iterator mapIter = m_ScriptEventListenerMap.find(eventID);

      while(m_ScriptEventListenerMap.end() != mapIter)
      {
      //Iterate through and ensure no duplicates
      const ScriptEventListenerPtr evtListener = mapIter->second;
      const LuaObject & evtObj = evtListener->GetHandlerFunction();
      if(evtObj == callbackFunction)
      {
      assert(0 &&"Attempted to listen to the same event handler twice!");
      return false;
      }
      ++mapIter;
      }


      The code finds a map entry with the a particular eventID. then it enters a while loop in which it iterates through the list to check for duplicates, this involves grabbing the entries Callback function and checking to see if it is the same as the one being added by this function.

      the code then iterates through the rest of the entries/types in the ListenerMap and checks to see if the function is registered to any other entries. Does this mean that a callback function is only suppost to be registered once and is not suppost to be registered for more than 1 type?

      if so why do we search for a particular event type before the loop and not just loop through the whole list?
    • I catched this too. Because the ScriptEventListenerMap is actually a std::multimap the code should be changed to something like the following in my opinion.

      this goes into the EventManagerImpl.h:

      Source Code

      1. // Holds the result of an equal_range search in the multimap
      2. typedef std::pair<ScriptEventListenerMap::iterator, ScriptEventListenerMap::iterator> ScriptEventListenerRes;


      this replaces the code in EventManager::AddScriptListener:

      Source Code

      1. //OK, valid event type. Make sure this isn't a duplicate.
      2. ScriptEventListenerRes res = m_ScriptEventListenerMap.equal_range(eventID)
      3. ScriptEventListenerMap::const_iterator mapIter = res.first;
      4. while ( res.second != mapIter )
      5. {
      6. //Iterate through and ensure no duplicates.
      7. const ScriptEventListenerPtr evtListener = mapIter->second;
      8. const LuaObject & evtObj = evtListener->GetHandlerFunction();
      9. if ( evtObj == callbackFunction )
      10. {
      11. assert( 0 && "Attempted to listen to the same event handler twice!" );
      12. return false;
      13. }
      14. ++mapIter;
      15. }
      Display All


      Same changes would apply to the EventManager::RemoveScriptListener method.

      equal_range reference: cplusplus.com/reference/stl/multimap/equal_range/