Search code examples
ember.jsember-cli

How to create reusable code with ember.computed?


I am totally new to ember, and after a lot of hours of searching I couldn't figure out how to make reusable code with Ember.computed properties. Here is an example: I have two controllers which have similar part of code for sorting arrays(they recieve different models)

export default Ember.Controller.extend({
    sortProps: ['createdAt:desc'],
    sortedPosts: Ember.computed.sort('model', 'sortProps'),
    last3SortedPosts: Ember.computed('sortedPosts', function() {
    return this.get('sortedPosts').slice(0,3);
}),

...

and I wish not to write it twice. Is there a way to do this?


Solution

  • In mixins/sorted-posts.js

    export default Ember.Mixin.extend({
      sortProps: ['createdAt:desc'],
      sortedPosts: Ember.computed.sort('model', 'sortProps'),
      last3SortedPosts: Ember.computed('sortedPosts', function() {
        return this.get('sortedPosts').slice(0,3);
      })
    });
    

    In your controller:

    import SortedPostsMixin from '../mixins/sorted-posts';
    
    export default Ember.Controller.extend(SortedPostsMixin, {
    /* .. */
    });