Plugin to allow a class to easily broadcast events

Example
var Mammal = define(comb.plugins.Broadcaster, {
  instance : {

     constructor: function(options) {
         options = options || {};
         this._super(arguments);
         this._type = options.type || "mammal";
     },

     speak : function() {
         var str = "A mammal of type " + this._type + " sounds like";
         this.broadcast("speak", str);
         this.onSpeak(str);
         return str;
     },

     onSpeak : function(){}
   }
});


var m = new Mammal({color : "gold"});
m.listen("speak", function(str){
     //called back from the broadcast event
      console.log(str);
});
m.speak();
            

Constructor

Defined plugins/Broadcaster.js Source
function (){
   this.__listeners = {};
           
}
            

broadcast Function Public


Defined plugins/Broadcaster.js

Broadcasts an event from an object

Arguments Source
function (topic,args){
   args = Array.prototype.slice.call(arguments, 0);
   topic = args.shift();
   if (topic && topic in this.__listeners) {
       var list = this.__listeners[topic], i = list.length - 1;
       while (i >= 0) {
           list[i--].cb.apply(this, args);
       }
   }
           
}
    

listen Function Public


Defined plugins/Broadcaster.js

Listens to a broadcasted event Simimlar to comb.listen

Arguments Returns Source
function (topic,callback){
   if (!func.isFunction(callback)) {
       throw new Error("callback must be a function");
   }
   var handle = {
       topic: topic,
       cb: callback
   };
   var list = this.__listeners[topic];
   if (!list) {
       list = (this.__listeners[topic] = [handle]);
       handle.pos = 0;
   } else {
       handle.pos = list.push(handle);
   }
   return handle;
           
}
    

unListen Function Public


Defined plugins/Broadcaster.js

Disconnects a listener Similar to comb.unListen

Arguments Source
function (handle){
   if (handle) {
       var topic = handle.topic;
       if (topic in this.__listeners) {
           var listeners = this.__listeners, list = listeners[topic];
           if (list) {
               for (var i = list.length - 1; i >= 0; i--) {
                   if (list[i] === handle) {
                       list.splice(i, 1);
                       break;
                   }
               }
           }
       }
   }
           
}
    

License

MIT https://github.com/C2FO/comb/raw/master/LICENSE

Meta