为其中一个模板排序一个observableArray [英] Sorting an observableArray for one of the templates
问题描述
我有以下视图模型:
function instance(id, FirstName){
$.extend(this, {
id: ko.observable(id || ''),
FirstName: ko.observable(FirstName || '')
});
}
我在observableArray中有一些实例:
I have some instances in an 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进行排序.
In first ul
I need to render templates without sorting, in the second one render sorted by FirstName.
有人可以解释如何做吗?
Can anyone explain how to do it?
推荐答案
一个选项是添加一个代表可排序数组的dependentObservable.看起来像这样:
One option would be to add a dependentObservable that represents the sorted array. It would look something like:
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))的副本(不想对真实数组进行排序).
So, do a case insensitive comparison of the value of the FirstName observable of each item. Return a copy of the array (slice(0)) that is sorted (don't want to sort the real array).
此处提供示例: http://jsfiddle.net/rniemeyer/93Z8N/
有关Knockout版本2.0及更高版本的说明:ko.dependentObservable现在是ko.computed.参见从属可观察对象
Note regarding Knockout Version 2.0 and greater: ko.dependentObservable is now ko.computed. See Dependent Observables
这篇关于为其中一个模板排序一个observableArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!