July 18, 2012

Event system in JavaScript

If you're a web developer and you're using a lot of libraries like Backbone.js you'll know that there are certain cases where you need to listen to some event, but there really isn't a good way of doing so without making something really ugly and terrible. Or maybe there is...

What if I tell you that there's something like D-Bus but in JavaScript? Yeah... I was amazed too.
In fact the whole thing isn't anything made-by-aliens-for-aliens ©® , it's just something I never thought it can be done.

The idea is to have a global var and use addEventListener and dispatch from wherever you like.

So, maybe you're not too sure how exactly is that helpful. Let me tell you what am I working on right now, and why I need something like that.

The project I'm working on will let users upload files without refreshing the page (a la AJAX), but without using HTML5 goodies (yeah, they are awesome, but there are a lot of browsers that just don't support features like those yet). The only solution for doing so is uploading the file from a form inside an iframe. Bad part is that we can't really know when the upload finished and what was the result. Nah, scratch that! We can if we use EventBus!

We just need to listen for the right event:

And make the answer from the server call EventBus:

Note that in order to access the scope of our page from the iframe we use window.top.window.

There are a lot more situations where magic like this is needed, and I'm glad I discovered this little piece of art.

Kudos to the autor of this library!

Edit (1.5 years later): If you're using AngularJS, which you should if you're doing some serious client side coding, you can user $emit and $on, which will do basically the same as EventBus.