Last Updated: February 25, 2016
·
688
· 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();
    })

  }

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside