对 ArrayController 的内容进行排序 [英] Sort content of ArrayController
问题描述
我有一个 Ember.ArrayController
有一个未排序的内容.
I have a Ember.ArrayController
that has an unsorted content.
我想知道是否可以在不使用新属性的情况下对 ArrayController 的内容进行排序.
I want to know if its possible to sort the content of an ArrayController without using a new property.
我当然可以创建一个新属性:
I could of course create a new property:
App.MyArrayController = Em.ArrayController.extend({
mySortMethod: function(obj1, obj2) {
// some code here
},
updateSortedContent: function() {
var content = this.get('content');
if (content) {
var sortedContent = content.copy();
sortedContent.sort(this.mySortMethod);
this.set('sortedContent', sortedContent);
}
}.observes('content')
});
但我希望有更好的方法不重复内容.
But I hope there is a better way that does not duplicates the content.
推荐答案
UPDATE
最新版本的 Ember 实际上内置了排序功能.ArrayController
现在包括 Ember.SortableMixin
,如果您指定 sortProperties
(Array) 和可选的 sortAscending
(布尔值).
The latest version of Ember actually has sorting built in. ArrayController
now includes the Ember.SortableMixin
which will engage if you specify sortProperties
(Array) and optionally sortAscending
(Boolean).
注意:使用新的SortableMixin,您仍然需要参考arrangedContent
来获取排序版本.模型本身将保持不变.(感谢 Jonathan Tran)
Note: with the new SortableMixin, you still need to refer to arrangedContent
to get the sorted version. The model itself will be left untouched. (Thanks to Jonathan Tran)
App.userController = Ember.ArrayController.create({
content: [],
sortProperties: ['age'],
sortAscending: false
})
原答案
正确的做法是使用 ArrayProxy 的 arrangedContent
属性.此属性旨在被覆盖以提供内容数组的排序或过滤版本.
The correct way to do this is to use the arrangedContent
property of ArrayProxy. This property is designed to be overridden to provide a sorted or filtered version of the content array.
App.userController = Ember.ArrayController.create({
content: [],
sort: "desc",
arrangedContent: Ember.computed("content", function() {
var content, sortedContent;
content = this.get("content");
if (content) {
if (this.get("sort") === "desc") {
this.set("sort", "asc");
sortedContent = content.sort(function(a, b) {
return a.get("age") - b.get("age");
});
} else {
this.set("sort", "desc");
sortedContent = content.sort(function(a, b) {
return b.get("age") - a.get("age");
});
}
return sortedContent;
} else {
return null;
}
}).cacheable()
});
这篇关于对 ArrayController 的内容进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!