Class comb.plugins.Broadcaster
Defined in: Broadcaster.js.
Class Detail
comb.plugins.Broadcaster()
Plugin to allow a class to easily broadcast events
Example 1 :
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();
this.__listeners = {};
Method Detail
broadcast(name, args)
Broadcasts an event from an object
- Parameters:
- name
- the name of the event to broadcast
- {Object|String|Function|Date|Number} args Optional
- variable number of arguments to pass to listeners, can be anything
var 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);
}
}
{Array}
listen(topic, callback)
Listens to a broadcasted event
Simimlar to comb.listen
- Parameters:
- {String} topic
- the topic to listen to
- {Function} callback
- the function to callback on event publish
- Returns:
- {Array} handle to disconnect a topic
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(handle)
Disconnects a listener
Similar to comb.unListen
- Parameters:
- handle
- disconnect a handle returned from Broadcaster.listen
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;
}
}
}
}
}
Documentation generated by JsDoc Toolkit 2.4.0 on Tue Jan 31 2012 16:14:12 GMT-0600 (CST)