Knockout Computed Subscription to unclared observable

时间:2014-05-06 13:48:27

标签: knockout.js subscriptions

有没有办法手动添加或删除计算的淘汰赛订阅?在我想要添加对尚未声明的observable的订阅的场景中,或者作为可能更改的属性。

即:

self.myComputed = ko.computed(function() {
   return "Value Is: " + self.myObservable();
})

self.myObservable(1);
//self.myComputed returns "Value Is: 1"

然后:

self.myObservable = ko.observable(2);  //new observable to property
//some code to add subscription to self.myComputed here
self.myObservable(3);
//self.myComputed returns "Value Is: 3" now

我意识到有解决问题的方法(例如只是重复使用self.myObservable作为下一个值)但我有时想手动修改订阅。

1 个答案:

答案 0 :(得分:1)

我真的不明白你为什么要这样做,但你可以创建一个计算引用属性名称而不是值的可观察对象。

self.myComputed = function () {
    return "Value is "+self["myObservable"]();
};
self.myObservable(1);
self.myComputed(); // Returns "Value is 1"

var oldMyObservable = self.myObservable;
self.myObservable = ko.observable(2);
self.myComputed(); // Returns "Value is 1", since the computed hasn't updated

oldMyObservable.notifySubscribers(); //force myComputed to recompute
self.myComputed(); // Returns "Value is 2"

当然,我认为包含可观察物的观察物的方法更清晰;但我认为上面的方法很有趣,可以发布。