Thursday, September 9, 2010

Message Oriented Architecture (Code 2/2)

Second and final part of the code.
private function _addEventListener(idChannel:String, type:String, listener:iEventListener):void {
   if(!(idChannel in hashChannel)) { // first add channel check
      // there is no hashType for that sender so we create one
      hashChannel[idChannel] = new Object();
   }
   if (!(type in hashChannel[idChannel])) { // first add type check
      // there is no such event listener registred
      hashChannel[idChannel][type] = new Array();
   }
   var array:Array = hashChannel[idChannel][type] as Array;
   if(array.indexOf(listener) != -1) { // second add listener check
      // the array does contain "listener", so we don't add twice
      return;
   } else {
      // the only really useful code
      array.push(listener);
   }
}
 
Be careful with all those checks, without them, you could have problems. By example if you put the EventCenter as an external project like me, you don't have to change for each project the type of channels, types etc. So keep in mind that you need to check each time if the channel exist, if the type exist etc. The code itself is not complex but the number of case could me it hard to understand. Now you know of to add a listener. Let's see of to remove on, that is the last part.
private function _removeEventListener(idChannel:String, type:String, listener:iEventListener):void {
   if(!(idChannel in hashChannel)) {
      // there is no hashType for that sender so we return
      return;
   }
   var hashType:Object = hashChannel[idChannel];
   if (!(type in hashType)) {
      // You try to remove a listener that has not the good type
   } else {
      var array:Array = hashType[type] as Array;
      var index:int = array.indexOf(listener);
      if(index != -1) {
         // remove the listener from the array
         array.splice(index, 1);
         if (array.length == 0) {
            // the array is empty, so we delete it
            delete hashType[type];
         } else {
            hashType[type] = array;
         }
      } else {
         // the listener is not in the array
      }
   }
}
 
The splice method of Array, permit the deletion when we specify the index of the item and 1 as the number of item we want to remove. When we need Array.remove(item), we need to use Array.splice(Array.indexOf(item), 1), but be careful, if you forget to write the "1" all the array from the index will be removed, quite hard to find in debug.
I think we are done with the subject of EventCenter, good luck using this new way of messaging.

No comments:

Post a Comment