当使用 Ember 单击时,如何为项目指定类。我正在对表的元素使用 Handlebars 操作来按属性排序。我想向正在排序的属性添加一个类,以便我可以向用户显示当前正在排序的属性。我怎样才能做到这一点?
我有一个 ember Controller ,如下所示:
App.UsersController = Ember.ArrayController.extend
title: 'Users'
count: Ember.computed.alias 'length'
sortProperties: ['username']
actions:
sort: (property) ->
console.log property
if @get('sortProperties')[0] is property
@set('sortAscending', !@get 'sortAscending')
else
@set 'sortProperties', [property]
@set('sortAscending', true)
Controller 允许我单击表格中的标题来对表格进行排序。 html如下所示:
<thead>
<tr>
<th>Action</th>
<th class="sort" {{action sort 'last'}}>Last</th>
<th class="sort" {{action sort 'first'}}>First</th>
<th class="sort" {{action sort 'username'}}>Username</th>
<th class="sort" {{action sort 'email'}}>Email</th>
</tr>
</thead>
最佳答案
创建 currentSort
属性(可选)
首先,我创建了一个currentSort
您的属性(property) App.UsersController
这清理了一些代码。我们稍后会用到它。
App.UsersController = Ember.ArrayController.extend
sortProperties: ['username']
currentSortBinding: 'sortProperties.firstObject'
actions:
sort: (sort) ->
if sort is @get('currentSort')
@toggleProperty 'sortAscending'
else
@setProperties
currentSort: sort
sortAscending: true
为每个 <th>
定义一个自定义 View
然后您将拥有to define a custom view对于<th>
这将做两件事:
- 上课
active-sort
当 View 的排序为当前时 - 在
click
时更改 Controller 当前排序查看 View
它看起来像这样:
App.SortView = Ember.View.extend
template: Ember.Handlebars.compile('{{view.sortName}}')
tagName: 'th'
sortName: null # (will be different for each <th> : `last`, `first`,..)
classNameBindings: [ ':sort', 'isCurrent:active-sort' ]
isCurrent: (->
@get('sortName') is @get('controller.currentSort')
).property('sortName', 'controller.currentSort')
click: ->
var newSort = @get('sortName');
@get('controller').send('sort', newSort);
我们在这里customized the view class names ,我们handled click
event on the view .
为每种排序插入自定义 View
这真的很简单insert views in templates :
<thead>
<tr>
{{view App.SortView sortName="default"}}
{{view App.SortView sortName="price"}}
{{view App.SortView sortName="alphabetical"}}
</tr>
</thead>
您可以测试所有这些 in a working JSBin
关于Ember.js 将类添加到操作帮助器模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25287929/