Sorting model in controller


#1

ember.js version: 2.18.0

model:

export default DS.Model.extend({

  name: DS.attr('string'),
  description: DS.attr('string'),
  songs: DS.hasMany('song')
})

controller:

export default Controller.extend({
  sortBy: ['name:asc', 'description:asc'],
  sortedBands: computed.sort('model', 'sortBy')
}

ember gave me the following error:

Only string, number, symbol, boolean, null, undefined, and function are allowed as default properties ember/avoid-leaking-state-in-ember-objects


#2

I had the same issue yesterday and found this blog post: https://dockyard.com/blog/2015/09/18/ember-best-practices-avoid-leaking-state-into-factories

tl;dr

Don’t use objects (arrays) as default properties on Ember.Objects because they would be shared by all instances of this Ember.Object.

You should use a computed property

sortBy: computed(function() {
  return ['name:asc', 'description:asc'];
})

or set the property in the init hook

init() {
  this._super(...arguments);
  this.sortBy = ['name:asc', 'description:asc'];
}

#3

An object class variable defaults to a static variable really is a quirk. Thanks anyway.


#4

I think the lesson learned is that try to use the Object interface methods as much as possible instead of the JavaScript primitives. If that makes sense.

For example: this.get(’’), this.set(’’,’’), computed properties, init(){ this._super(…arguments). I think you’d run into less issues. Use Ember’s Object Model until they migrate off it :stuck_out_tongue:


#5

Another option rather than adding an init function is to freeze the array, as I did here:

filteredReimbursementsSorting: Object.freeze(['ride.start']),

This follows the example of Ember superstar Robert Jackson, it seems less intrusive to me.


#6

@backspace Thanks for the link. I like “your” solution much better.


#7

You’re welcome. I like it much more too, the init thing looks so invasive, this feels like it keeps it more declarative rather than imperative.


#8

@backspace Used Object.freeze with Ember 2.18 but get this error in IE 11.


#9

Just tested and this bug is still present in 3.0.0-beta.6