是否可以使属性依赖于另一个对象的所有属性?例如:(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
,而必须手动指定所有属性(如注释掉的代码中所示)?
答案 0 :(得分:1)
不,但是编写一个监视所有内容的观察者并且触发您的计算属性以在其更新时随时更新是非常容易的。我不一定推荐这个,但可以做到。
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')
您可以选择仅使用属性执行类似操作,而不是观察: