I just came across this series of posts about JavaScript, and they’re great! They cover the most recent technologies in the front-end scene nowadays. Among them, there was a concept that I had never heard of before: mediated events. When you use (for instance) jQuery’s on, you’re saying that whenever an event is triggered by an element, a callback must be launched.
With mediated events, you don’t have that tight coupling. Instead, elements (and any other kind of event publisher) publishes events about a certain topic on a certain channel with some attached data. Then, some other objects subscribe callbacks to those channels and topics. You could have different channels and, within those, different topics.
In this example, I’m going to use postal.js, one of the most popular libraries for this kind of tasks. I’ve set up a MeteoGuy who publishes reports on the status of the wind and rain. Also, I’ve set up two listeners who are subscribed to wind and rain-related events respectivelly. As you can see, the listeners are not subscribed to TheMeteoGuy directly, but to TheWeatherChannel.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
var TheMeteoGuy = { report : function (concept, newStatus) { postal.publish({ channel : 'TheWeatherChannel', topic : concept + "." + newStatus, data : { status : newStatus } }); }, reportSunnyDay : function () { this.report('Wind', 'stops'); this.report('Rain', 'stops'); } }; var WindEventListener = postal.subscribe({ channel : "TheWeatherChannel", topic : "Wind.*", callback : function (data, envelope){ console.log('Something happened with the wind! It ' + data.status); } }); var RainEventListener = postal.subscribe({ channel : "TheWeatherChannel", topic : "Rain.*", callback : function (data, envelope){ console.log('Something happened with the rain! It ' + data.status); } }); TheMeteoGuy.report('Wind', 'improves'); TheMeteoGuy.report('Rain', 'worsens'); TheMeteoGuy.reportSunnyDay(); |
To better see the power of these kind of messages you could, for instance, add a NewspaperWeatherSection that would publish to the same TheWeatherChannel, and the listeners would receive the messages as well.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
var NewspaperWeatherSection = { reportSomething : function () { var concept = ['Wind', 'Rain'][_.random(0,1)]; var status = ['improves', 'worsens', 'stays'][_.random(0,2)]; postal.publish({ channel : 'TheWeatherChannel', topic : concept + "." + status, data : { "status" : status } }); } }; NewspaperWeatherSection.reportSomething(); |
As you can see, the posibliities behind this are endless. However, here’s a word of caution. If you abuse this, you’ll end up with a lot of messages being sent from everwhere, and no easy way of tracking them.