UPDATE
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).
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
})
ORIGINAL ANSWER
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()
});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…