javascript - 当可观察数组中的对象的属性更新时,如何使可观察数组通知其依赖项?

标签 javascript knockout.js

我将下面的数组绑定(bind)到一个模板

function Customer(id, name){
   this.Id = ko.obserable(id);
   this.Name = ko.obserable(name);
}

var customer1 = new Customer(1, "a");
var customer2 = new Customer(2, "b");

var customers = [customer1, customer2];

var oa = ko.observableArray(customers);

oa.subscribe(function(newValues){
   //How to force trigger this when a customer property gets updated?
});

当我在 View 上更新客户名称时,数组中有更新的数据,但它不会通知它的订阅者。我如何解决这个问题并强制通知其订阅者?

最佳答案

您可以使用计算的 值来自动跟踪值列表中的更改。您在计算函数中解包的每个可观察对象都会创建一个依赖项。

唯一的缺点:您不知道哪个更改导致了更新。如果那是您所需要的,您需要订阅各个 Name observables。

这是一个使用自定义相等比较器来保持整洁的示例。您也可以只让 hash 返回一个 string 并在订阅者方法中手动解包 oa

function Customer(id, name){
   this.Id = ko.observable(id);
   this.Name = ko.observable(name);
   this.toString = () => `(${this.Id()}) ${this.Name()}`;
}

var customer1 = new Customer(1, "a");
var customer2 = new Customer(2, "b");

var customers = [customer1, customer2];

var oa = ko.observableArray(customers);

var oaHash = ko.pureComputed(() => ({ 
  hash: oa().map(c => c.Name()).join("||"),
  newValues: oa()
}));

oaHash.equalityComparer = (a, b) => a === b || a && b && a.hash === b.hash;

oaHash.subscribe(function ({ newValues }) {
  console.log(
    "Something changed, I now contain:",
    newValues.map(c => c.toString()).join(", ")
  );
});

customer1.Name("Jane");
oa.push(new Customer(3, "c"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

关于javascript - 当可观察数组中的对象的属性更新时,如何使可观察数组通知其依赖项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56295177/

相关文章:

php - 如何将自定义参数传递给 jqGrid 中内联编辑的 ajax 请求

javascript - 如何完全实现消息轮询的服务器发送事件

knockout.js - knockout 显示选择数据

javascript - 如何在应用程序中显示实时 console.logs?

javascript - 传递 ajax header 信息时出现问题

javascript - .getElementById 的内联 SVG 和 HTML DOM 范围

javascript - 检查拖放列表的正确顺序

javascript - 在knockout JS中绑定(bind)复杂模型

带有 SignalR 和 KnockoutJS 的大型项目的 Javascript

javascript - 集合教程中的 ko.observable 变量