Provider” is a JavaScript programming pattern that I’ve found myself using more and more of late.

A Provider is an asynchronous function that can be called to provide a particular resource, if there is a need for it.  The Atom functions .need() and .provide() exist for just this purpose.

var
  a = atom.create(),
  need = a.need,
  provide = a.provide,
  json2src = 'https://raw.github.com/douglascrockford/JSON-js/master/json2.js'
;

// If JSON is built-in or already loaded, use that.
// Else, load Crockford's.
provide('JSON', function (done) {
  if (typeof JSON !== 'undefined') {
    done(JSON);
  } else {
    loadScript(json2src, function () {
      done(JSON);
    });
  }
});

need('JSON', function (JSON) {
  // Safely call JSON functions in all browsers.
  console.log(JSON.stringify(document.location));
});

Providers in Atom are nice because:

  • They only get invoked if necessary — that is, if there is a need and if the property is not already set — so you benefit from lazy loading; and,
  • They get invoked at most once, even if multiple consumers call .need()
  • Resources are just Atom properties, so you can use them with other Atom functions, too.

More about Atom:

Advertisements