Question

Currently I have a computed observable similar to:

// Backed with either an observable array or an observable of an array
var underlying = ko.observable([..]);

var obs = ko.computed({
   read: function () { return underlying(); },
   write: function (items) {
      // Process items - basically, I have the parent collection quickly
      // subscribe to an observable on each item. This in and of itself
      // should likely be cleaned up, but is not the focus of this question.
      // For instance:
      items.forEach(function (i) {
         if (!subscribed(i.title)) {
           i.title.subscribe(removeItemWhenEmptyTitle);
         }
      });

      underlying(items);
   }
});

However, I would like to be able to treat this computed observable like an observable array such that I can call obs.push(..) and such.

It's somewhat trivial to hack this up, but it doesn't feel right and I don't want to duplicate all of the existing observable array methods.

obs.push = function (item) {
  var arr = obs();
  arr.push(item);
  obs(arr);
});

Also, I might be missing a crucial difference between an observable array and an observable of an array.

Was it helpful?

Solution

Moved from comment:

The easiest path for you looks like just using an observableArray, and then subscribing to it to do your processing, since you are bot manipulating the value before it has been written.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top