cat-t
cat-t

Reputation: 1376

Sorting an array in a component

I'm trying to pass results into a component and then have the component sort it:

// data passed to component
{
    type: 'people',
    res : [
      {name: 'charlie', age: '55'},
      {name: 'bobby', age: '19'},
      {name: 'raymond', age: '39'}
    ]
}

// component
App.ShowResultsComponent = Ember.Component.extend({

    // note sure how to set up array controller
    sorted : Ember.ArrayProxy.create({
        content : this.get('results.res')
    }),

)}

my jsbin

I'm not sure if I'm missing/misunderstanding some fundamental, but is it possible to include an array controller as a property in a component? Any clarification would be appreciated.

Upvotes: 4

Views: 1880

Answers (2)

patmood
patmood

Reputation: 1585

You can also extend the component with Ember.SortableMixin, then use arrangedContent as you normally would in a controller.

  App.ShowResultsComponent = Ember.Component.extend(Ember.SortableMixin, {

    ...

  });

Here is your JSBin updated for Ember 1.9.1 and using the Sortable Mixin

Upvotes: 9

melc
melc

Reputation: 11671

Yes it is possible to instantiate an array controller as a computed property in order to take advantage of the sortable mixin functionality.

js

....
App.ShowResultsComponent = Ember.Component.extend({

  // not sure how to set up array controller
  sorted : function(){
    return Ember.ArrayController.create({
     content : this.get('results.res')
  });

  }.property(),

  actions: {
    sortAge: function(){
      this.get("sorted").set("sortProperties",["age"]);
      this.get("sorted").toggleProperty("sortAscending");
    },
    sortName: function(){
      this.get("sorted").set("sortProperties",["name"]);
      this.get("sorted").toggleProperty("sortAscending");
    }
  }

});
....

hbs

....
<h3>Sorted:</h3>
    <ul>
      {{#each sorted.arrangedContent}}
        <li>{{name}} -- {{age}}</li>      
      {{/each}}
    </ul>
....

http://emberjs.jsbin.com/bubiramuhi/1

Upvotes: 4

Related Questions