In May, I released a small JavaScript library called Atom.  Though only a couple of Kb minified, it is nonetheless very useful for a number of things, and my team at Zynga has been using it for almost all new projects we’ve started in the past few months.

In this post, I want to demonstrate a common and useful pattern that we use Atom for, which we call the Barrier pattern.

The essence of the Barrier pattern is that we have some code that we want to be run only after a certain set of conditions are met. To accomplish this, we need use only two Atom methods: .once() and .set().

var
  a = atom.create(),
  once = a.once,
  set = a.set
;

once(['cleanedRoom', 'brushedTeeth'], function () {
  sayGoodnight();
  goToBed();
});

In the example above, the two conditions are represented by the ‘cleanedRoom’ and ‘brushedTeeth’ properties of an atom instance. We don’t care which order they are completed in — only that they are both completed as a prerequisite to saying goodnight and going to bed.

The Atom method .once() lets us register a callback that gets called as soon as some combination of properties gets set, so it suits the purpose of the simple barrier above nicely.  However, we also have access to the value of the properties, which can be useful:

if (typeof jQuery !== 'undefined') {
  set('$', jQuery);
} else {
  loadScript('//code.jquery.com/jquery-1.8.3.min.js', function () {
    set('$', jQuery.noConflict());
  });
}

once('$', function ($) {
  $(function () {
    set('body', $(document.body));
  });
});

once(['body', '$'], function (body, $) {
  body.append('We have jQuery and can start manipulating the DOM!');
  // ...
});

This example is a robust usage of jQuery, that does not depend on jQuery already being loaded prior. If jQuery is not detected at the start, we make an asynchronous call to load it. Either way, as soon as we’re sure it exists, we set the ‘$’ property.

With Atom, when you use .set() to set a value for a property, it will trigger any listeners for that property immediately. So we have not only set up a barrier for code to wait for jQuery before executing, but we also provide a safe reference to it (on the highlighted lines).

I hope it’s easy to see how the barrier pattern as enabled by Atom can easily be used to make sure that your code gets run as soon as the necessary prerequisites are set, and not before. For more information about Atom, read the README.

Advertisements