简体   繁体   中英

Is there a way to detect whether any element of a nested structure of observables has changed?

Is there a single emitter that can fire if any observable element of viewModel.data() has changed, or do I need to loop through and subscribe to each of the independent observables?

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

You can use a computed observable to "subscribe" to multiple observable at the same time. Any observable that has its value accessed in the evaluation of the computed observable will become a dependency.

So, you can do something like:

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

If you want to subscribe to all observables in some object graph, then an easy way to do it, is to use ko.toJS . In your example, you might want to do:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM