1

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.

3
  • Since, it looks like you are not manipulating the value being written, you could just use an observableArray, and then subscribe to it to do your processing. Commented Oct 29, 2013 at 1:09
  • @RPNiemeyer I've updated my code a bit to show the gist of what I am attempting the the write. The "Y" problem revolves around letting a parent subscribe/react to an observable in a child - e.g. when a child's title observable is set to "", remove the child/item from the parent collection. Commented Oct 29, 2013 at 1:12
  • @RPNiemeyer Oh, oh. Right. Yes I could do that. Commented Oct 29, 2013 at 1:18

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.