使计算属性依赖于emberjs中另一个对象的所有属性

时间:2013-11-25 22:30:52

标签: javascript ember.js

是否可以使属性依赖于另一个对象的所有属性?例如:(also in jsfiddle):

HTML:

<script type="text/x-handlebars" >
    {{outlet}}
</script>

<script type="text/x-handlebars" data-template-name="index">
    <p>Weapon damage: {{ input value=model.activeWeapon.damage}} </p>
    <p>Hero damage: {{ model.weaponDamagePerSecond }}</p>
</script>

的javascript:

App = Ember.Application.create({});

App.Weapon = Ember.Object.extend({
    damage: null,
    speed: null
});

App.Hero = Ember.Object.extend({
    activeWeapon: null,
    strength: null,
    weaponDamagePerSecond: function() {
      var weapon = this.get('activeWeapon');
      console.log('weapon damage:' + weapon.get('damage'));
      console.log('weapon speed:' + weapon.get('speed'));
      console.log('strength:' + this.get('strength'));
      console.log (weapon.get('damage') + this.get('strength')) * weapon.get('speed');

      return (1.0 * weapon.get('damage') + 1.0 * this.get('strength')) * weapon.get('speed');
    }.property('activeWeapon', 'strength')
    //}.property('activeWeapon.damage', 'activeWeapon.speed', 'strength')
    // the above line will make the example work, but it is a bit painful to 
    // have to specify all the attributes needed of activeWeapon.
});

App.IndexRoute = Ember.Route.extend({
    model: function() {
        return App.Hero.create({
            activeWeapon: App.Weapon.create({
                damage: 40,
                speed: 2
            }),
            strength: 8
        });
    }
});

weaponDamagePerSecond上的任何属性更新时,是否可以更新activeWeapon,而必须手动指定所有属性(如注释掉的代码中所示)?

1 个答案:

答案 0 :(得分:1)

不,但是编写一个监视所有内容的观察者并且触发您的计算属性以在其更新时随时更新是非常容易的。我不一定推荐这个,但可以做到。

http://jsfiddle.net/5gS59/

App.Weapon = Ember.Object.extend({
    damage: null,
    speed: null,
    version: 0,
    watchingEverything: function(){
        console.log('hello');
        this.incrementProperty('version');
    }.observes('damage','speed')
});


weaponDamagePerSecond: function() {
  var weapon = this.get('activeWeapon');
  console.log('weapon damage:' + weapon.get('damage'));
  console.log('weapon speed:' + weapon.get('speed'));
  console.log('strength:' + this.get('strength'));
  console.log (weapon.get('damage') + this.get('strength')) * weapon.get('speed');

  return (1.0 * weapon.get('damage') + 1.0 * this.get('strength')) * weapon.get('speed');
}.property('activeWeapon.version', 'strength')

您可以选择仅使用属性执行类似操作,而不是观察:

http://jsfiddle.net/XsuxA/1/