gpt4 book ai didi

javascript - Knockout.js 有类似 AngularJS 过滤器的东西吗?

转载 作者:行者123 更新时间:2023-11-28 15:19:34 28 4
gpt4 key购买 nike

内置概念,因此可以很容易地将数据集缩减为与用户输入等匹配的元素。

有类似的东西吗? ?

当然,我可以使用普通的旧 Javascript 自己实现它,但我不是性能专家,所以我自己的解决方案可能会非常慢。

最佳答案

是的,Steve Sanderson已创建knockout-projections knockout 插件。

这类似于 Angular 过滤器,您可以将映射或过滤器应用于源集合以生成另一个集合以绑定(bind)到 UI。

这个来自项目 github readme 的示例演示了用法并解释了 mapfilter 回调如何高效执行:

Mapping

More info to follow. For now, here's a simple example:

var sourceItems = ko.observableArray([1, 2, 3, 4, 5]);

There's a plain observable array. Now let's say we want to keep track of the squares of these values:

var squares = sourceItems.map(function(x) { return x*x; });

Now squares is an observable array containing [1, 4, 9, 16, 25]. Let's modify the source data:

sourceItems.push(6);
// 'squares' has automatically updated and now contains [1, 4, 9, 16, 25, 36]

This works with any transformation of the source data, e.g.:

sourceItems.reverse();
// 'squares' now contains [36, 25, 16, 9, 4, 1]

The key point of this library is that these transformations are done efficiently. Specifically, your callback function that performs the mapping is only called when strictly necessary (usually, that's only for newly-added items). When you add new items to the source data, we don't need to re-map the existing ones. When you reorder the source data, the output order is correspondingly changed without remapping anything.

This efficiency might not matter much if you're just squaring numbers, but when you are mapping complex nested graphs of custom objects, it can be important to perform each mapping update with the minumum of work.

Filtering

As well as map, this plugin also provides filter:

var evenSquares = squares.filter(function(x) { return x % 2 === 0; });
// evenSquares is now an observable containing [36, 16, 4]

sourceItems.push(9);
// This has no effect on evenSquares, because 9*9=81 is odd

sourceItems.push(10);
// evenSquares now contains [36, 16, 4, 100]

Again, your filter callbacks are only called when strictly necessary. Re-ordering or deleting source items don't require any refiltering - the output is simply updated to match. Only newly-added source items must be subjected to your filter callback.

关于javascript - Knockout.js 有类似 AngularJS 过滤器的东西吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32101131/

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