如果viewModel.data()的任何可观察元素发生了变化,是否有一个发射器可以触发,或者我是否需要遍历并订阅每个独立的observable?
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()}
])
}
]),
答案 0 :(得分:2)
您可以使用计算的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);
如果要订阅某个对象图中的所有可观察对象,那么一种简单的方法就是使用ko.toJS
。在您的示例中,您可能希望这样做:
ko.computed(function() {
ko.toJS(vm.data); //will create dependencies on all observables inside "data"
//run some code
}, vm.data);