Sorting an observableArray for one of the templates

匿名 (未验证) 提交于 2019-12-03 02:56:01

问题:

I have the following view model:

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

I have some instances in an observableArray:

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

With the following template:

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

And another template:

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

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?

回答1:

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); 

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).

Sample here: http://jsfiddle.net/rniemeyer/93Z8N/

Note regarding Knockout Version 2.0 and greater: ko.dependentObservable is now ko.computed. See Dependent Observables



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!