Sorting an observable array, which has queried data returned by breezeJS

血红的双手。 提交于 2019-12-12 05:49:39

问题


The above image is of observableArray which is coming while queryinq database using breezeJS (using EntityManager).

My question is that

how do we sort this observable based on some criteria i.e., (object.attributeName) ?

So that this array is sorted based on some attribute name and we can simply use the observable within foreach bindings and use them in sorted way because I don't wanna query all the time (locally or from server) to get data in sorted order.


回答1:


So make a computed

var orderDirection = ko.observable(1);
var orderField = ko.observable("id");
var orderedObsArr = ko.computed(function(){
     var oDir = orderDirection();
     var oField = orderField();
     var newArr = originalObsArr().slice(0);
     newArr.sort(function(a,b){
         return oDir * (a[oField] > b[oField] ? 1 : -1);
     });
     return newArr;
});

so to change to a sort by name descending, you simply change:

orderDirection(-1);
orderField("name");

and your computed dependent orderedObsArr will be updated.

See this pen for a working example.



来源:https://stackoverflow.com/questions/30913848/sorting-an-observable-array-which-has-queried-data-returned-by-breezejs

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