Commits

Rune Halvorsen  committed 450a1cb

Tweaked method names and made initialization lazy

  • Participants
  • Parent commits d8c6c1c

Comments (0)

Files changed (1)

File templates/js/messagemixin.js

 /**
  * Mix in class that lets arbitrary classes act as message sources. The
- * mixin adds the public methods addListener, removeListener and postMessage.
- * There is also the method post which is an alias of postMessage. It is
- * deprecated and will be removed eventually.
+ * mixin adds the public methods add_listener, remove_listener and post_message.
+ * There are aliases, called post, addListener and removeListener, these are
+ * deprecated and will at some point be removed.
  *
  * Note that the presence of a _public_ post method means anyone can
  * dispatch messages on an object, not just the object itself.
 
 function MessageMixin()
 {
-  this._mm_listeners = {};
 
   /**
    * Add a message listener
    * @param name {String} The name of the message to listen for
    * @param cb {function} The callback to call when message is received
    */
-  this.addListener = function(name, cb)
+  this.add_listener = function(name, cb)
   {
-    if(this._mm_listeners[ name ] )
+    if(! this._mm_listeners)
+    {
+      this._mm_listeners = {};
+    }
+
+    if( name in this._mm_listeners)
     {
       this._mm_listeners[ name ].push( cb );
     }
       this._mm_listeners[ name ] = [ cb ];
     }
   };
+  this.addListener = this.add_listener;
 
   /**
    * Remove a listener for a specific message.
    * @param name {String} the name of the message to dispatch
    * @param cb {Object} the callback function for the message.
    */
-  this.removeListener = function(name, cb)
+  this.remove_listener = function(name, cb)
   {
+    if (! this._mm_listeners) { return false; }
     var cur = null;
     var listeners = this._mm_listeners[ name ] || [];
     var i = 0;
         i--;
       }
     }
+    return true;
   };
+  this.removeListener = this.remove_listener;
 
   /**
    * Post a message to all its listeners, optionally with a payload. The
    * @param name {String} the name of the message to dispatch
    * @param msg {Object} the payload to the message. Optional
    */
-  this.postMessage = function( name, msg )
+  this.post_message = function( name, msg )
   {
+    if (! this._mm_listeners) { return false; }
     msg = msg || {};
-
     var listeners = this._mm_listeners[ name ] || [];
     var cb = null;
     var i = 0;
     {
       cb(msg);
     }
+    return true;
   };
-
-  this.post = this.postMessage;
+  this.post = this.post_message;
 }