Last Updated: February 25, 2016
·
456
· mpj

fetchingProperty for Knockout.js

/**
   * A Knockout Subscribable that is dependent on
   * an asynchronous function for fetching it's value,
   * such as a database call with a callback.
   *
   * @param  {Function} fetcher      The function that does the fetching of
   *                                 the property value. The fetcher should accept
   *                                 one argument, a setter, which is simply a function
   *                                 that accepts the fetched value as it's single argument.
   * @param  {Object}   initialValue The initial value for the property (before the first fetch
   *                                 has completed.)
   * @return {Subscribable}          A Knockout Subscribable.
   */
  function fetchingProperty(fetcher, initialValue) {
    var cache = ko.observable(initialValue);

    var subComputed = computedLazy({
      deferEvaluation: true,
      read: function() {
        fetcher(cache);
      }
    });

    var firstRun = true;

    return computedLazy(function() {
      if (firstRun) {
        firstRun = false;
        subComputed();
      }
      return cache();
    })

  }