CustomEvent to communicate web apps in the same page

Due the increasing number of front-end framework out there, you might find yourself in a situation where you need to communicate two or more web apps living in the same page, let’s say, an AngularJS application used mostly with directives that need some way to talk to the Menu controller, which happen to have been built in BackboneJS. A solution for this that I personally favor is the use of the CustomEvent API, mainly because it works great with these constrains:

  • Your current applications need to stay almost as they are, stand alone and independent of each other.
  • No need of a new centralized controller or structure.
  • No need to add an external library.

In the case where you require certain level of communication among your internal apps, mainly to notify changes in the UI or update shared models, CustomEvents offers you the following advantages:

  •  Very low coupling
  •  Preserve app independency
  •  Low impact on bandwith and CPU performance (i.e. a light-weight solution, not a megalosaurus air traffic control)

I came up with an idea to help us to get this, based on how DOM events work (http://bitovi.com/blog/2010/10/a-crash-course-in-how-dom-events-work.html)

Custom Events

It’s possible to create a custom Event object by using the class CustomEvent, putting inside it any data we want, via ‘detail’ property. As with any other DOMevent (click, mouseover, etc) it can be seamlessly listened by anybody who wants to do so.

 

And then, anybody within your same page can listen to “myPageEvent” in the following way:

 

Indeed, this is basically an Observer (Publish/Subscribe) pattern out-of-the-box in modern web browsers, where all webapps living in the same page are listening to a broadcast of custom events. With the great advantage this is very light-weight, supported by all modern browsers, we avoid any sort of application registry and feels completely natural with how JavaScript applications work.

Drawbacks:

  • There is indeed low security, so be aware when sending critical information. Everything it’s good for basically just UI interactions.
  • No < IE8 support. Fortunately there are polyfills for CustomEvents and we might want to include this polyfill to our own custom version of JQuery broacaster.

Naturally, this solution is not new nor groundbreaking, but still impress me how little is known and how complicated can get other alternatives. As a side note, Twitter built an entire framework based on this principle, called Flight, which you should check out.
Finally, the demo contains an AngularJS and a Backbone application, living in the same page and listening to Ui interactions from each other. If you see at the console, vanilla JavaScript is also listening to this events;

See a demo | Code

So, what do you guys think about it?