0

如果 viewModel.data() 的任何可观察元素发生变化,是否有一个发射器可以触发,或者我是否需要循环并订阅每个独立的可观察对象?

data: ko.observable([
      {
        name: "Chart Position",
        fields: ko.observableArray([
          {name: "marginBottom", type: "percOrNumber", value: ko.observable(), valueType: ko.observable()},
          {name: "marginLeft", type: "percOrNumber", value: ko.observable(), valueType: ko.observable()},
          {name: "marginRight", type: "percOrNumber", value: ko.observable(), valueType: ko.observable()},
          {name: "marginTop", type: "percOrNumber", value: ko.observable(), valueType: ko.observable()}
        ])
      }
    ]),
4

1 回答 1

2

您可以使用计算的 observable 同时“订阅”多个 observable。在计算的 observable 的评估中访问其值的任何 observable 都将成为依赖项。

因此,您可以执行以下操作:

ko.computed(function() {
    this.one();  //just accessing the value for a dependency
    this.two();  //doesn't matter if we actually use the value
    this.three();

    //run some code here or if you have a reference to this computed observable, then you can even do a manual subscription against it.
}, vm);

如果你想订阅某个对象图中的所有 observable,那么一个简单的方法就是使用ko.toJS. 在您的示例中,您可能想要执行以下操作:

ko.computed(function() {
   ko.toJS(vm.data);  //will create dependencies on all observables inside "data"

   //run some code
}, vm.data);
于 2012-05-10T16:22:31.757 回答