如果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()}
        ])
      }
    ]),

最佳答案

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

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

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


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

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

   //run some code
}, vm.data);

关于javascript - 有没有一种方法可以检测可观测对象的嵌套结构的任何元素是否已更改?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10537997/

10-09 16:06