I was discussing OpenAjax Hub which is an implementation of the publisher-subscriber pattern last week with my client. In the process, decided to quickly hand-toss my own implementation of the pattern.
Here’s an example where there’is a textbox and a button. When the user enters a value in the textbox and hits the button, the value is published to a list of subscribers. The subscribers are pre-registered with the button.
<html> <head> <script> var Bus = function(){ var subscribers = []; this.publish = function(eventName,arg){ var handlers = subscribers[eventName]; for(var i=0;i<handlers.length;i++){ handlers[i](arg); } } this.subscribe = function(eventName,handler){ if(!subscribers[eventName]) subscribers[eventName] = []; subscribers[eventName].push(handler); } }; var messageBus = new Bus(); function init(){ messageBus.subscribe("btnclick",handler1); messageBus.subscribe("btnclick",handler2); } function doSomething(){ messageBus.publish("btnclick",document.getElementById("nametext").value); } function handler1(arg){ document.getElementById("spn1").innerHTML = "<b>" + arg + "</b>"; } function handler2(arg){ document.getElementById("spn2").innerHTML = "<i>" + arg + "</i>"; } </script> </head> <body onload="init();"> Name <input type="text" id="nametext"><input type="button" value="Do" onclick="doSomething()"><br/> <span id="spn1"></span><br/> <span id="spn2"></span><br/> </body> </html>
The code has a Bus class with publish/subscribe methods. The subscribe() method adds the handler functions to a collection and publish() method invokes the handlers.