Autowiring components to a message bus in Javascript

When writing AJAX and SOFEA/SOUI applications, it's a best practice to use a client side message bus to integrate UI components. People recognized this as a best practice lately for GUI development with Swing. As a sidenote Werx was excellent for this but sadly is dead.

One of the ways to do message buses in Javascript is the OpenAjax Hub implementation or TIBCO PageBus.

Subscribing to messages on the bus is easy with the subscribe method:

jo.ListComponent = function() {
  OpenAjax.hub.subscribe("list.get") { 
    function(event, publisherData, subscriberData) {
      // do something when message arrives

When you have lots of those subscriptions though, they clutter up your code. Werx had the nice idea to autowire methods to messages and use the methods as message handlers. I thought I should do the same for Javascript and OpenAjax Hub.

jo.ListComponent = function() {
  this.$list_get = function(list) {
    // do something with list
  // connect the methods

Some magic happens in the connect method.

jo.connect = function(object) {
  for (var element in object) {
    if (element.charAt(0) == '$') {
      var event = element.substring(1).replace(/_/g, ".");
      var callback;
      // we need to capture the scope
      (function() {
        var fn = object[element];
        callback = function(event, data) {
          fn.apply(object, [data]);
      jo.Bus.subscribe(event, callback);

The same could be achieved with a map of message handlers which is easy with functions in Javascript whereas in Java it takes more boiler code. A solution with methods as messages handlers as seen above has the benefit though that the object can contain other helper methods and state, which a map of message handlers can not. Using autowired methods makes your message bus code cleaner and more readable.

Thanks for listening.

Stephan Schmidt Administrator
CTO Coach , svese
Stephan is a CTO coach. He has been a coder since the early 80s, has founded several startups and worked in small and large companies as CTO. After he sold his latest startup he took up CTO coaching. He can be found on LinkedIn or follow him in Twitter.
follow me