Why Ember computed macros not support for setter


#1

Why Ember compute macros not support for setter


#2

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


#3

@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.


#4

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

Check the source.


#5

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


#6

@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 !


#7

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


#8

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')
});

#9

@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?