doWhen

It occurs to me that I have neglected to post about the most bloody useful utility I’ve ever written: doWhen

While the main version is a jQuery plugin, I find myself using the non-jQuery version more often, so that’s the one I’ll describe here.

What doWhen does is allow you to create a single “virtual event” in the form of a test function which, when it returns true, runs a callback function.

Let’s say we were loading a library and wanted a quick way to do something when the library is ready:

<script type="text/javascript">
var global = (function(){return this;}());
Event.doWhen(function(){
  return !!global.jQuery;
}, function(){
  alert('jQuery loaded!');
});
</script>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.min.js"></script>

The !! ensures the result is a boolean. Every 100 milliseconds (configurable), it will run the first function. The first time that function returns true, it runs the second function.

I use this extremely frequently, even in wee code snippets, thanks to the tiny footprint (about 1/3kB minified).

See the github page for options.

Open question: is Event the place to put this? Keep in mind this isn’t extending the object’s prototype, so shouldn’t cause conflicts in other code.

I am considering whether there’s a need for an ajax capable one which periodically checks a remote state.