4

So I have a model in Ember that is generating a hash with three objects. One of the objects is an array of objects with another array inside each object. I need to sort this innermost array, but I am having trouble doing so.

Here are my models.

App.Person = DS.Model.extend ({
    first_name: DS.attr('string'),
    last_name: DS.attr('string'),
    age: DS.attr('string'),
    gender: DS.attr('string'),
    innerMostArray: DS.hasMany('innerMostObject')
});

App.innerMostObject = DS.Model.extend ({
    person_id: DS.belongsTo('person'),
    attr1: DS.attr('string'),
    attr2: DS.attr('string')
});

Here is my Route

App.NestedArrayRoute = Ember.Route.extend({
    model: function(params) {
        return Ember.RSVP.hash({
            object1: this.store.find('object1', params.object1_id),
            people: this.store.all('person'),
            object3: this.store.all('object3')
        });
    },
    afterModel: function(model, transition) {
        model.people.forEach(function(item, index, enumerable){
            var innerMostArray = item.get('innerMostArray');
            var sortedArray = innerMostArray.sortBy('attr1', 'attr2');
        });
        model.people.update();
    } 
});

I know that I am nowhere near doing this right but I just don't know how to sort this nested array. I've seen examples of array controllers, but I don't know how to use one to sort this nested array. If anyone could give an example of how to do this it would be very helpful. Thank you.

2 Answers 2

5

I agree with Kalmans answer, but I suggest you do this sorting with built-in methods to save you trouble:

App.Person = DS.Model.extend({
   name: DS.attr('string'),
   fruits: DS.hasMany('fruit', {async: true}),
   fruitSorting: ['title', 'color'],
   sortedFruits: Ember.computed.sort('fruits', 'fruitSorting')
});

I forked his example here: http://emberjs.jsbin.com/manutu/1/edit?html,js,output

Sign up to request clarification or add additional context in comments.

3 Comments

That looks great! I like it :)
Sort is not the only built-in feature, take a look here for the functions starting with Ember.computed. : emberjs.com/api/classes/Ember.html
Oh I do like this method more. I think this one is easier to understand.
3

One way to do this is to create a computed property on the model as follows:

App.Person = DS.Model.extend({
  name: DS.attr('string'),
  fruits: DS.hasMany('fruit', { async: true }),
  sortedFruits: function(){
    var fruits = this.get('fruits');
    return fruits.sortBy('title', 'color');
  }.property('[email protected]', '[email protected]')
});

Working example here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.