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();
function (){
this.__listeners = {};
}
Broadcasts an event from an object
Argumentsvariable number of arguments to pass to listeners, can be anything
the name of the event to broadcast
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);
}
}
}
Listens to a broadcasted event Simimlar to comb.listen
Argumentsthe topic to listen to
the function to callback on event publish
Array handle to disconnect a topic
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;
}
Disconnects a listener Similar to comb.unListen
Argumentsdisconnect a handle returned from Broadcaster.listen
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;
}
}
}
}
}
}
MIT https://github.com/C2FO/comb/raw/master/LICENSE
git clone git://github.com/C2FO/comb.git