gpt4 book ai didi

对模板之一的 observableArray 进行排序

转载 作者:行者123 更新时间:2023-12-03 07:21:11 27 4
gpt4 key购买 nike

我有以下 View 模型:

function instance(id, FirstName){
$.extend(this, {
id: ko.observable(id || ''),
FirstName: ko.observable(FirstName || '')
});
}

我在 observableArray 中有一些实例:

 ko.observableArray([new instance(...), new instance(...), ...]

使用以下模板:

<ul data-bind='template: {name: "instanceTemplate", foreach: instances}'></ul>

另一个模板:

<ul data-bind='template: {name: "anotherInsTmpl", foreach: instances}'></ul>

在第一个ul中,我需要渲染模板而不排序,在第二个渲染中按FirstName排序。

谁能解释一下怎么做吗?

最佳答案

一种选择是添加一个 dependentObservable 来表示已排序的数组。它看起来像:

viewModel.sortFunction = function(a, b) {
return a.FirstName().toLowerCase() > b.FirstName().toLowerCase() ? 1 : -1;
};

viewModel.sortedInstances = ko.dependentObservable(function() {
return this.instances.slice().sort(this.sortFunction);
}, viewModel);

因此,对每个项目的 FirstName 可观察值的值进行不区分大小写的比较。返回已排序的数组 (slice(0)) 的副本(不想对真实数组进行排序)。

示例:http://jsfiddle.net/rniemeyer/93Z8N/

有关 Knockout 2.0 及更高版本的注意事项:ko.dependentObservable 现在为 ko.compulated。请参阅Dependent Observables

关于对模板之一的 observableArray 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6965951/

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