Ember.js 将类添加到操作帮助器模板

标签 ember.js handlebars.js

当使用 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/

相关文章:

ember.js - 如何在 ember-cli 中渲染后触发元素功能

java - 如何正确格式化 Hibernate 实体以与 ember-data 一起使用?

javascript - 基本 'if' 语句在 handlebars JS 中不起作用

backbone.js - 具有辅助功能的 Handlebars 逻辑运算

javascript - 是否可以将渲染函数放入 Express 的 for 循环中?

javascript - 使用 Promise 加载主干模板

javascript - 有没有办法在 ember REST 适配器中支持嵌套资源?

javascript - Ember Data的查找方法: handling SQL 'OR' equivalent query

Handlebars 中的 Javascript "any string"正则表达式?

ember.js - 如何在 EmberJS 中同时出现操作错误和渲染模板