【问题标题】:Create a computed observable that acts like an observableArray?创建一个类似于 observableArray 的计算 observable?
【发布时间】:2013-11-07 23:56:36
【问题描述】:

目前我有一个类似的计算 observable:

// 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);
   }
});

但是,我希望能够像 observable array 一样处理这个计算出的 observable,这样我就可以调用 obs.push(..) 等。

破解这个有点微不足道,但感觉不对,我不想复制所有现有的可观察数组方法。

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

另外,我可能遗漏了可观察数组和可观察数组之间的关键区别 of

【问题讨论】:

  • 因为看起来你并没有操纵正在写入的值,你可以只使用一个 observableArray,然后订阅它来进行处理。
  • @RPNiemeyer 我已经稍微更新了我的代码,以显示我正在尝试write 的要点。 “Y”问题围绕着让 parent 订阅/对子中的 observable 做出反应 - 例如当孩子的可观察的标题设置为“”时,从 parent 集合中删除孩子/项目。
  • @RPNiemeyer 哦,哦。正确的。是的,我可以这样做。

标签: knockout.js observable computed-observable


【解决方案1】:

从评论中移出:

对您来说最简单的方法是使用 observableArray,然后订阅它来进行处理,因为您是在值被写入之前对其进行操作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-29
    • 2012-12-09
    • 1970-01-01
    相关资源
    最近更新 更多