dagda1
dagda1

Reputation: 28810

Drying up ember.js computed properties

I have a collection of computed properties that are all very similar:

WZ.ExercisesHomeController = Em.ArrayController.extend
  content: Ember.A()

  arms: ( -> 
          @filterProperty('group.name', 'Arms')
        ).property('@each.isArms')

  abs:  ( -> 
          @filterProperty('group.name', 'Abs')
        ).property('@each.isAbs')

  back: ( -> 
          @filterProperty('group.name', 'Back')
        ).property('@each.isBack')

  chest: ( -> 
          @filterProperty('group.name', 'Chest')
        ).property('@each.isChest')

  legs: ( -> 
          @filterProperty('group.name', 'Legs')
        ).property('@each.isLegs')

Is there any way I can change this to one property, possibly a set propety?

Upvotes: 2

Views: 826

Answers (1)

Ryan
Ryan

Reputation: 3594

Yes. Use a function that returns this filter function.

var filterFn = function(name) {
  return function() {
    return this.filterProperty('group.name', name);
  }.property('@each.is' + name);
};

Ember.ArrayController.create({
  arms: filterFn('Arms'),
  legs: filterFn('Legs'),
  ...
});

You can even dynamically add the filtering functions by using Ember's reopen.

App.ArrayController = Ember.ArrayController.extend();

var names = ['Arms', 'Legs', ...];

var toAdd = {};
names.forEach(function(name) {
  toAdd[name] = filterFn(name);
});

App.ArrayController.reopen(toAdd);

Upvotes: 3

Related Questions