Ad-hoc custom computed property macro

Is it possible to create custom computed property macro for specific use case?

Example:

I have an ember object with properties that share most of the logic. This logic is extracted into it’s own method. What I don’t like is that I have to repeat dependent keys, because it’s easy to misspell.

// ember object
....
secondValues: computed('values.@each.time', function() {
    let steps = 60 * 1000;
    return this.getValues(steps, start, end);
}),

hourValues: computed('values.@each.time', function() {
    let steps = 60 * 60 * 1000;
    return this.getValues(steps, start, end);
}),
//... and so on

It would be nice if I could turn that method into custom computed macro that would be specific for this model. The macro would know what properties it depends on so I could omit the dependent keys when declaring properties.

// computedTimeValues is custom macro

secondValues: computedTimeValues(60 * 1000),
hourValues: computedTimeValues(60 * 60 * 1000),

Is something like this possible? Or is it in general bad idea? I’ve never created custom macro so I’m not sure how to do that.

Thanks

Hi @ondrejsevcik — you can absolutely do that (and it’s a pattern I really like!)

I think, in your case, it would just be a matter of creating a method called computedTimeValues that returns the computed property. Something like:

import { computed } from '@ember/object';

function computedTimeValues(steps) {
  return computed('values.@each.time', function() {
    // ...not sure where start/end come from
    return this.getValues(steps, start, end);
  });
}
1 Like

That’s very neat, thanks!

1 Like