如何在ember组件中对{{#each}}进行排序

时间:2015-06-08 19:28:46

标签: javascript ember.js

我在{{#each}} {{/each}}中有一个列表。 如何在ember组件中对此列表进行排序?

组件/会话-list.hbs

{{#each model as |conversation|}}
{{conversations-item userName=conversation.contact.userName lastConversationTime=conversation.lastConversationTime profilePictureUrl=conversation.contact.profilePictureUrl id=conversation.id}}
{{/each}}

我如何按lastConversationTime排序此列表?

2 个答案:

答案 0 :(得分:1)

找到答案:

fooSorting: ['id:desc']

Ember.computed.sort('model' , fooSorting)



App = Ember.Application.create();

App.Router.map(function() {
  // put your routes here
});

App.Colors = [{
  id: 1,
  color: 'red'
}, {
  id: 2,
  color: 'yellow'
}, {
  id: 3,
  color: 'blue'
}];

App.IndexRoute = Ember.Route.extend({
  model: function() {
    return App.Colors;
  }
});

App.IndexController = Ember.Controller.extend({
  sorting: ['id:desc'],
  sortedContent: Em.computed.sort('model', 'sorting')
});

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Ember Starter Kit</title>
  <link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.1/normalize.css">
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  <script src="http://builds.emberjs.com/tags/v1.12.0/ember-template-compiler.js"></script>
  <script src="http://builds.emberjs.com/tags/v1.12.0/ember.debug.js"></script>

  <head>
    <meta charset="utf-8">
    <title>Ember Starter Kit</title>
    <link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/normalize/2.1.0/normalize.css">
  </head>

  <body>

    <script type="text/x-handlebars">
      <h2>Welcome to Ember.js</h2>
      {{outlet}}
    </script>

    <script type="text/x-handlebars" data-template-name="index">
      <ul>
        {{#each sortedContent as |item|}}
        <li>id: {{item.id}}: {{item.color}}</li>
        {{/each}}
      </ul>
    </script>


  </body>

</html>
&#13;
&#13;
&#13;

http://emberjs.com/api/classes/Ember.computed.html#method_sort

答案 1 :(得分:0)

正确的方式

在控制器初始化期间使用阵列控制器中的sortBy功能

init: function() {    
  this.model.sortBy('lastConversationTime'); //Requires the model to be of Ember.Array Type
},

http://emberjs.com/api/classes/Ember.Array.html#method_sortBy

使用SortableMixin:

http://emberjs.com/api/classes/Ember.SortableMixin.html

肮脏,蛮力的方式:

在控制器内部定义sortedModels变量,并按照您想要的顺序将当前模型设置为:

var sortedModels = [],
sortModelsBy(model, field) {
  //Add your sorting here
}
init: function() {    
  this.set('sortedModels', sortModelsBy(this.model, 'lastConversationTime'));
},

在模板内部调用sortedModels而不是

{{#each sortedModels as |conversation|}}
  {{conversations-item userName=conversation.contact.userName lastConversationTime=conversation.lastConversationTime profilePictureUrl=conversation.contact.profilePictureUrl id=conversation.id}}
{{/each}}