javascript - 有没有办法检测可观察对象的嵌套结构的任何元素是否已更改?

标签 javascript knockout.js

是否有一个发射器可以在 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/

相关文章:

javascript - promise reject not working with mysql 错误

javascript - 在 Angular 指令中获取父元素

Javascript:无法从本地存储中提取

html - 使用 HTML 属性进行 knockout validation

javascript - KnockoutJS observableArray 在通知订阅者之前是否会区分新旧数组?

javascript - 如何使用 KnockoutJS、SammyJS 和 pagerJS 组织 SPA

javascript - 如何使用KnockoutJS将数据保存到SQL数据库中?

javascript - knockout 日期验证无法正常工作

javascript - 使用 npm 安装 grunt-browser-sync 时出错

javascript - Rails 3 - 应用程序布局问题