* JavaScript Event Merging

Posted on July 14th, 2010 by Dave Johnson. Filed under JavaScript.

In a recent project I finally decided to write something to help with JavaScript event merging. There are often cases in JavaScript where you want some code to run but only after certain events have fired or other code run - in my case I wanted to execute a JavaScript function only after two different bits of code had executed. The most common use case for event merging I have come across has got to be on page load / DOM ready where you may need several conditions to be true before executing some JavaScript code.

Event merging generally helps you to better separate your concerns and not have unwieldy if conditions strewn throughout your code checking if certain condi.

If you have a basic JavaScript object called the “Subject” that has subscribe, subscribeOnce (events that auto-unsubscribe themselves after being fired the first time), and notify methods on them. You can use the following merge function to have all subscribed code executed only after each of the events passed to the merge function are fired. In this case I have explicitly used the subscribeOnce method on the event.

function merge(handler, events) {
       var i = events.length;
       var f = function() {
           if (!(--i)) handler();
       for (var j=0; j<i; j++) {
           var e = events[j];
       if (!i) handler();

When the merge function is called it iterates over all the events in the event array argument and checks if that event has already been fired or not by checking the “fired” property on the event - note that this makes it so that it doesn’t matter if merge is called before or after the events have fired. If the event has not been fired yet then a handler is attached using subscribeOnce where the handler checks a counter indicating how many of the events have been fired, once the counter hits 0 then the final handler for the merged events is called.

I have put up an entire event merging code on Github here.


Trackback URI | Comments RSS

Leave a Reply