【发布时间】: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