Why Ember computed macros not support for setter

Why Ember compute macros not support for setter

http://emberjs.com/api/classes/Ember.ComputedProperty.html#method_set

1 Like

@jamalsoueidan thank you, Its Ember.ComputedProperty, but I am asking about macros like Ember.computed.empty is not working fine while using setter as well as getter.

Ember’s computed macros cannot be used as setters, except Em.computed.alias.

Check the source.

@Manumie Is there any reason other compute macros work as only getter?

@Ylk

Because most of them return boolean values.

Say you have a character model (for a game) :

App.Character = Em.Object.create({
  id: null,
  life: 50,
  xp: 1,

  isDead: Em.computed.equal('life', 0);
});

isDead is true when life equals 0.

You can use it in your template :

...
{{#if isDead}}
  <p>Game Over</p>
{{else}}
  <p>game play</p>
{{/if}}
...

but it doesn’t make sense to set it : if you set it to false, how does your app know what value to set for life ?

Hope it helps !

1 Like

@Manumie Thank you, but in your case I can not set isDead as true without setting life as 0. Thats my concern too.

That’s the point, you cannot do it with Ember computed macros.

You can write your own computed property :

App.Character = Em.Object.create({
  id: null,
  life: 50,
  xp: 1,

  isDead: function(key, value) {
    // setter (check that value is set and strictly equals true)
    if ( value && (value === true) ) { 
      this.set('life', 0);
    }
    // in every case, return a boolean
    return ( this.get('life') == 0 );
  }.property('life')
});

@Manumie Thank you, I am already done this workaround but we can use Ember computed macros as setter and getter by default what you think?