Sorting a nested array within a model

Hey there,

I’ve always been using the following way to load a list of items from the backend:

App.ItemModel = Ember.Object.extend({
  foo: '',
  bar: 0
});

App.ItemModel.reopenClass({
  content: Ember.Object.create({
  }),
  load: function() {
    var content = this.content;
    content.set('isLoading', true);

    $.getJSON('some/url')
      .always(function() {
        content.set('isLoading', false);
      });
      .then(
        function(json) {
          // checking if any error messages returned etc.
          content.set('items', json.items);
        }, 
        function() {
          content.set('error', 'server error');
        }
      );

    return content;
  }
});

The controller:

App.ItemController = Ember.ObjectController.extend({
    filteredItems: function() {
        return this.get('items').filterBy(
          this.get('filterField'), 
          this.get('filterValue')
        );
    }.property('items.[]', 'filterField', 'filterValue')
});

Handlebars:

{{#if isLoading}}
  <p>Items are being loaded...</p>
{{else}}
  {{#if error}}
    <p>{{error}}</p>
  {{else}}
    {{#each filteredItems}}
        ...
    {{/each}}
  {{/if}}
{{/if}}

Now I want to be able to sort the items too. How can I make use of ArrayController?

Take a look at http://emberjs.com/guides/controllers/representing-multiple-models-with-arraycontroller/ for a guide on how to use sorting with arraycontroller.

1 Like

Hey,

Thanks for the reply. I can change my ItemController to extend from ArrayController and return an array from ItemModel.load() function. But how do I handle load errors & loading state then?

What you’ve got in the code there looks fine, so if there’s an ajax error it’ll show an error, if not it’ll show the list of items.