broadcast
The broadcast
plugin works like pub sub hub. You can subscribe to messages and publish messages with an optional data
property. Messages recieved take the form of a gui.Broadcast
. The message string may by identified
by the type
property.
gui.Spirit.extend({
onconfigure: function() {
this.super.onconfigure();
this.broadcast.add('mybroadcast');
},
onbroadcast: function(b) {
this.super.onbroadcast(b);
switch(b.type) {
case 'mybroadcast':
console.log(b.data);
break;
}
}
});
You'll need another spirit to dispatch the broadcast.
gui.Spirit.extend({
onready: function() {
this.super.onready();
this.broadcast.dispatch('mybroadcast','mydata');
}
});
Multiple listeners
You can add and remove multiple broadcast listeners with an array or space-separated string. Just make sure that the individual messages don't contain spaces.
this.broadcast.add([BROADCAST1, BROADCAST1, BROADCAST3]);
this.broadcast.remove('broadcast1 broadcast2 broadcast3');
When adding a listener, you can setup up to automatically remove it once the broadcast is received.
this.broadcast.one('mybroadcast'); // TODO: implement!
Get the dispatcher
When you recieve a broadcast, you can identify the dispatcher using the target
property. The dispatcher is most likely another spirit.
gui.Spirit.extend({
onbroadcast: function(b) {
this.super.onbroadcast(b);
console.log(b.target); // [object gui.Spirit]
}
});
Global broadcasts
You can broadcast messages across iframes
using the methods outlined below. Spiritual GUI must be loaded in all frames for this to work.
this.broadcast.addGlobal('mybroadcast');
this.broadcast.dispatchGlobal('mybroadcast');
It's important to synchronize addGlobal
and dispatchGlobal
. You cannot intercept a global broadcast using a local listener even if publisher and subscriber is in the same window.
Broadcast anywhere
You can dispatch a broadcast outside of a spirit.
gui.Broadcast.dispatch('mybroadcast', 'mydata');
You can subsribe to a broadcast from anywhere.
gui.Broadcast.add('mybroadcast', {
onbroadcast: function(b) {
console.log(b.type); // 'mybroadcast'
}
});