ember.js #each order by property

2019-02-24 14:19发布

问题:

I have an array of Ember.Objects which is displayed by Handlebars {{#each}} helper which I want to be sorted by an property of those objects everytime the array changes.

So something like this:

var arr = [
    Ember.Objects.create({
        position:0,
        label:"foo"
    }),
    Ember.Objects.create({
        position:1,
        label:"bar"
    }),
];

And the handlebar

{{#each arr}}
    <div class="label">{{label}}</div>
{{/each}}

So if I update the positions and the bar object becomes first, I want the view to be updated. Can I depend the {{#each}} Helper on an property?

回答1:

You have to use an ArrayController proxy on your data, and set the sortProperties attribute. Then, use the controller as the each data source.

Sample @ http://jsfiddle.net/MikeAski/Epjqp/

Using the controller as the data source provides an arranged content. Take care not to use directly the controller's content, as it is the raw source data...