2012-05-10 57 views
0

如果viewModel.data()的任何可觀察元素髮生了更改,還是需要遍歷並訂閱每個獨立的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()} 
     ]) 
     } 
    ]), 

回答

2

您可以使用計算的觀察值同時「訂閱」到多個觀察值。在計算可觀測值的評估中有任何可訪問的值的觀測值將成爲依賴項。

所以,你可以這樣做:

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

啊,這真的很酷,謝謝RP! –

相關問題