lou*_*uio 8 arrays sorting ember.js
我有一个Ember.ArrayController没有未分类的内容.
我想知道是否可以在不使用新属性的情况下对ArrayController的内容进行排序.
我当然可以创建一个新属性:
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')
});
Run Code Online (Sandbox Code Playgroud)
但我希望有一种更好的方法不会重复内容.
Iva*_*van 35
UPDATE
最新版本的Ember实际上已经内置了排序.ArrayController现在包括Ember.SortableMixin如果你指定sortProperties(数组)和可选sortAscending(布尔),它将参与.
注意:使用新的SortableMixin,您仍需要参考arrangedContent以获取排序版本.模型本身将保持不变.(感谢Jonathan Tran)
App.userController = Ember.ArrayController.create({
content: [],
sortProperties: ['age'],
sortAscending: false
})
Run Code Online (Sandbox Code Playgroud)
原始答案
执行此操作的正确方法是使用arrangedContentArrayProxy 的属性.此属性旨在覆盖以提供内容数组的已排序或已过滤版本.
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()
});
Run Code Online (Sandbox Code Playgroud)