Reputation: 616
I have a list within a {{#each}} {{/each}}
.
How would I sort this list in an ember component?
components/conversations-list.hbs
{{#each model as |conversation|}}
{{conversations-item userName=conversation.contact.userName lastConversationTime=conversation.lastConversationTime profilePictureUrl=conversation.contact.profilePictureUrl id=conversation.id}}
{{/each}}
How would I sort this list by lastConversationTime?
Upvotes: 1
Views: 3448
Reputation: 616
Found the Answer:
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>
http://emberjs.com/api/classes/Ember.computed.html#method_sort
Upvotes: 1
Reputation: 10040
The right way
Use the sortBy
function in array controller during your controller init
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
Or
Use the SortableMixin:
http://emberjs.com/api/classes/Ember.SortableMixin.html
The dirty, brute-force way:
Inside your controller define a sortedModels
variable and set your current model to that in the order you want it:
var sortedModels = [],
sortModelsBy(model, field) {
//Add your sorting here
}
init: function() {
this.set('sortedModels', sortModelsBy(this.model, 'lastConversationTime'));
},
Inside your template call sortedModels
instead
{{#each sortedModels as |conversation|}}
{{conversations-item userName=conversation.contact.userName lastConversationTime=conversation.lastConversationTime profilePictureUrl=conversation.contact.profilePictureUrl id=conversation.id}}
{{/each}}
Upvotes: 0