我将下面的数组绑定(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/