使计算属性依赖于emberjs中另一个对象的所有属性
Making a computed property dependent on all the properties of another object in emberjs
是否可以使一个属性依赖于另一个对象的所有属性?例如:(也在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
});
}
});
当activeWeapon
上的任何属性更新时,是否可以让weaponDamagePerSecond
更新,而不必手动指定所有属性(如注释掉的代码)?
没有,但编写一个观察者非常容易,它可以监视所有内容,并在计算属性更新时触发其更新。我不一定建议这样做,但这是可以做到的。
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/
相关文章:
- 如果使用 lodash 将属性存在于另一个对象中,则向对象添加属性
- 你能用来自数组的属性名称生成一个对象吗
- 将javascript对象(属性+值)合并到一个对象中
- 如何计算一个对象中五个属性中有多少是非null的
- 获取一个对象´s属性的名称使用字符串
- JavaScript-通过类似的属性查找对象,并将其推送到一个新的数组中
- 通过另一个对象上的字符串值为 javascript 对象属性赋值
- Join验证对象数组,这样只有一个对象具有特定属性
- Javascript:如何制作一个包含4个具有相同属性的对象的数组
- 将值和属性从一个对象合并到另一个对象
- 替换对象's属性,其中包含JavaScript中另一个对象的属性,不包含库
- 有没有一个lodash函数可以合并两个对象并删除其中一个对象的属性(如果它们没有)'不存在于另一个中
- Javascript:我如何定义一个对象'的属性
- 使计算属性依赖于emberjs中另一个对象的所有属性
- 检查数组中的对象属性是否与具有相同ID的另一个对象重复
- 将对象属性放在另一个对象中
- 将一个对象的属性替换为另一个对象的属性
- 如何检查一个对象是否嵌套在另一个对象的属性中作为属性
- Javascript 使用 $.extend 按值复制,但只有一个对象属性
- 根据另一个对象中的键和属性从数组中删除对象