gpt4 book ai didi

knockout.js - 敲: Is it bad form to iterate through observable arrays with ko utility methods?

转载 作者:行者123 更新时间:2023-12-04 02:45:38 27 4
gpt4 key购买 nike

来自 this post :

I would first suggest that you optimize your dependentObservable (a.k.a. computed). When you read any observable, Knockout registers a dependency to it in Dependency Manager...

I can see in your pseudo-code that you are accessing this.ParentList() in the while loop. It means registerDependency will be called 3000 times and the dependencies array will be scanned 3000 times, which is bad for IE (since it has no built-in Array.indexOf method).

So my number one suggestion would be: Read all observables before loops.

考虑到这个好建议,这是我的问题:

使用 ko 实用方法(如下所示)遍历 observable 数组是否是一种错误的形式? [假设 this.mySelectListItems() 是一个 observableArray]:

self.selectedValuesCount = ko.computed(function () {
var total = 0;
ko.utils.arrayForEach(this.mySelectListItems(), function (item) {
if (item.selected() === true) {
total += 1;
}
});
return total;
}, self);

换句话说,这样做有什么收获吗?

self.selectedValuesCount = ko.computed(function () {
var total = 0;
var myArray = this.mySelectListItems();
ko.utils.arrayForEach(myArray, function (item) {
if (item.selected() === true) {
total += 1;
}
});
return total;
}, self);

最佳答案

不,那些代码位完全相等。

如果您在移交给 arrayForEach 的回调中一次又一次地检索同一个可观察对象的值,您只会获得性能提升 - 但在这种情况下, observable 数组只被检索一次,所以没有必要将该数组放在一个额外的变量中。

关于knockout.js - 敲: Is it bad form to iterate through observable arrays with ko utility methods?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11037273/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com