1.0.1 • Published 7 years ago

joinable-callback v1.0.1

Weekly downloads
1
License
ISC
Repository
-
Last release
7 years ago

joinable-callback

Allows callbacks to easily join in on the data fetching while it's in progress!

Example:

var joinableCallback = require('joinable-callback');

var htmlTemplates = {};

function createHtmlTemplateComponent(templateName) {
  var obj = htmlTemplates[templateName];

  if (!obj) {
    // not attempted yet - set up a new joinableCallback to do something when we have it in our hands!
    var cb = joinableCallback(function (templateBody) {
      createComponent(templateBody);

      // overwrite the joinableCallback with the real data
      htmlTemplates[path] = templateBody;
    });

    htmlTemplates[path] = cb;

    // load data
    $.get('/templates/' + templateName + '.html').done(function (data) {
      // it is loaded, trigger the callback.
      cb(data);
    });
  } else if (joinableCallback.isJoinableCallback(obj)) { // in progress - join in on the fun.
    res.join(function (templateBody) {
      // called when loaded
      createComponent(templateBody);
    });
  } else {
    // it is loaded at this point and stored in htmlTemplates, do something with it right away!
    createComponent(obj);
  }

  // function to handle when it's all loaded in
  function createComponent(templateBody) {
    /** put your logic here... */
  }
}