我正在尝试在 EmberJS 上实现 GroupableMixin ( https://github.com/ahawkins/ember.js/blob/groupable-mixin/packages/ember-runtime/lib/mixins/groupable.js ),但我在使用它时遇到了问题。
我想在我的 ArrayController 中指定一个 groupProperty (就像我们如何拥有 sortProperties 一样),并且我希望根据该属性来计算我的分组。
<小时/>我确实尝试过http://emberjs.jsbin.com/cawaq/3/edit这就是我得到的:
App.UsersIndexController = Ember.ArrayController.extend({
sortProperties: ['created_at'],
groupProperty: 'role',
groupedContent: groupBy('role'), //How do it reference groupProperty in groupBy?
//How can groupedContent be updated whenever groupProperty is changed?
});
我见过http://discuss.emberjs.com/t/ember-enumerable-no-group-by/3594/6和 http://jsbin.com/ukagip/2/edit但仍然不太清楚如何使其正常工作。
最佳答案
Hawkins 先生的 GroupableMixin
的意图和行为与 Ember 的 Discourse 论坛中讨论的非常不同。您似乎混淆了这两种方法。
混合方法(霍金斯先生)
请注意,这是我推荐的方法
GroupableMixin
是 Ember.Mixin
的一个实例,用于扩展对象的原型(prototype)。有关混合的更深入解释,请参阅 Coding Value's explanation .
我们可以通过阅读 tests for the mix-in 来确定混合要求和行为:
- 该类的行为必须类似于
ArrayProxy
(因此 ArrayController 就可以) - 必须为类设置
groupBy
属性
因此我们可以将此混合包含在数组 Controller 中,如下所示:
App.UsersIndexController = Ember.ArrayController.extend(Ember.GroupableMixin, {
groupBy: 'role'
});
现在我们已经满足了混合的要求,我们将可以免费访问一些新的计算属性和函数,例如groupedContent
。在不向 Controller 添加任何其他内容的情况下,我们可以在模板中编写类似的内容来访问组:
{{#each group in groupedContent}}
<h1>{{group.name}}</h1>
<ul>
{{#each user in content}}
<li>{{user.name}}</li>
{{/each}}
</ul>
{{/each}}
这是an example that groups words in an array controller by first letter .
计算辅助方法(a la Ember Sherpa)
此方法创建一个帮助器,它根据提供给函数的键定义计算属性。我们可以创建一个类似的函数来映射到 mix-in 的组接口(interface):
Sherpa = {};
Sherpa.groupBy = function (groupBy) {
var dependentKey = 'content.@each.' + groupBy;
return Ember.computed(dependentKey, function(){
var result = [];
this.get('content').forEach(function(item){
var hasGroup = !!result.findBy('name', get(item, groupBy));
if (!hasGroup) {
result.pushObject(Ember.Object.create({
name: get(item, groupBy),
content: []
}));
}
result.findBy('name', get(item, groupBy)).get('content').pushObject(item);
});
return result;
});
};
现在我们可以使用此函数创建一个 groupedContent
计算属性:groupedContent: Sherpa.groupBy('role')
这是an example which uses the same template as the previous example并且仅用此方法交换了混合。
推荐
使用GroupableMixin
,它比论坛中讨论的方法健壮得多:
- 论坛讨论的方法...
- 简单易懂
- 效率低下
- 只要数组或相关属性发生更改,就重新计算整个组数组
- 不实现用于查找的映射结构,而是通过数组迭代搜索
- 在任何计算的更改上取消所有 itemController:如果您选中 second example 中的某些框然后添加一个新单词,所有复选框都会被清除
- 混合...
- 是一个更强大但复杂的实现
- 处理组的插入和删除,而不是重新计算整个 map
- 为小组提供 map 支持,以提高绩效和效率
- 使用
itemController
时的行为符合预期:只需勾选复选框并在 the first example 中添加一些单词即可,您会发现这些复选框永远不会被清除
关于javascript - Ember GroupableMixin 使用 groupProperty,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24463951/