Emberjs advanced sort hasMany association as a computed property

245 views Asked by At

I have asked a variant of this question here. But basically I need to create a computed property that operated on a hasMany association. I need to do sorting similar to the javascript sort function; where I can do something like

files = ["File 5", "File 1", "File 3", "File 2"];
files.sort(function(a,b){
  return parseInt(b.split(' ').pop()) - parseInt(a.split(' ').pop())
});

result:

["File 5", "File 3", "File 2", "File 1"]

Here is my jsbin: http://emberjs.jsbin.com/simayexose/edit?html,js,output

Any help would be greatly appreciated.

Note: My jsbin presently is not working correctly (for reasons other then this question). I have posted a question about that here. I just did not want to hold up an answer to this question.

Update 1

Thanks @engma. I implemented the instructions. As a matter of fact, I copied and pasted what was posted. This is the new jsbin. http://emberjs.jsbin.com/roqixemuyi/1/edit?html,js,output

I still do not get anything sorted, though. And even if it did, it still would not have sorted the way I would like it.

I need something like the following: (below are errors that I get when I try to implement this in my code, not from jsbin, since I can not get jsbin to work)

  sortedFiles: function(){
    return this.get('files').sort(function(a,b){
      return parseInt(b.split(' ').pop()) - parseInt(a.split(' ').pop());
    });
  }.property('[email protected]')

When I do this I get the following error:

Uncaught TypeError: this.get(...).sort is not a function

So since this.get('files') returns a promise, I figured I would try this;

  sortedFiles: function(){
    return this.get('files').then(function(files){
      return files.sort(function(a,b){
        return parseInt(b.split(' ').pop()) - parseInt(a.split(' ').pop());
      });
    });
  }.property('[email protected]')

But then I get the following error:

Uncaught Error: Assertion Failed: The value that #each loops over must be an Array. You passed {_id: 243, _label: undefined, _state: undefined, _result: undefined, _subscribers: }

BTW, I am using emberjs v1.11.0

And, the sortBy I am using is ember-cli/node_modules/bower-config/node_modules/mout/array/sortBy.js

Here is the code for it

var sort = require('./sort');
var makeIterator = require('../function/makeIterator_');

    /*
     * Sort array by the result of the callback
     */
    function sortBy(arr, callback, context){
        callback = makeIterator(callback, context);

        return sort(arr, function(a, b) {
            a = callback(a);
            b = callback(b);
            return (a < b) ? -1 : ((a > b) ? 1 : 0);
        });
    }

    module.exports = sortBy;

Update 2

So to answer the question how to do an Emberjs advanced sort hasMany association as a computed property; I had to change

  this.get('files').sort(function(a,b){
      ...
  });

  return this.get('files').toArray().sort(function(a,b){
    ...
  });

This allowed me to use the javascript sort and return the desired sorted objects.

1

There are 1 answers

3
engma On BEST ANSWER

Ok first of all your JSBin had many issues so lets go throw them one by one

1- you did not include any Ember-Data build, so I included 1, this is needed for the fixtures and the models

<script src="http://builds.emberjs.com/tags/v1.0.0-beta.15/ember-data.js"></script>

2- Your Scripts

var App = window.App = Ember.Application.create({
});
//First this is how to register the adapter
App.ApplicationAdapter = DS.FixtureAdapter.extend({});

App.IndexRoute = Ember.Route.extend({
  model: function() {
    //Second with find you pass in the ID so I am using 1
    //if you want to get all folders use findAll()
    return this.store.find('folder',1);
  } 
});

App.IndexController = Ember.Controller.extend({

});


App.Router.map(function() {
});

App.Folder = DS.Model.extend({
  name: DS.attr('string'),
  files:  DS.hasMany('file',{async:true}),
  sortedFiles: function(){
    //Sorty By has no second parameter, if you need more sorting power, do it your self
    return this.get('files').sortBy('name');
  }.property('[email protected]')

});

App.File = DS.Model.extend({
  name: DS.attr('string'),
  folder: DS.belongsTo('folder',{async:true})
});

App.File.FIXTURES = [
  {
    id: 1,
    name: 'File 5',
    folder:1
  },
  {
    id: 2,
    name: 'File 1',
    folder:1
  },
  {
    id: 3,
    name: 'File 3',
    folder:1
  },
  {
    id: 4,
    name: 'File 2',
    folder:2
  },
  {
    id: 5,
    name: 'File 6',
    folder:2
  },
  {
    id: 6,
    name: 'File 4',
    folder:2
  }
];


App.Folder.FIXTURES = [
  { 
    id: 1,
    name: 'Folder 1',
    files:[1,2,3]
  },
  {
    id: 2,
    name: 'Folder 2',
    files:[4,5,6]
  }
];

Your Template:

<div>
   Folders: <br>
  <ul>
   <li>
     Name: {{model.name}} <br>
     Files:
     {{!-- here we access the sorted files property in the model--}}
     {{#each file in model.sortedFiles}}
       {{file.name}} <br/>
     {{/each}}
  </li>
 </ul>
</div>