gpt4 book ai didi

javascript - 为什么 Ember 观察者不对数组开火?

转载 作者:行者123 更新时间:2023-12-03 08:48:10 25 4
gpt4 key购买 nike

我正在尝试监听数组中每个元素的特定属性并从中获取结果。但是,更新似乎没有正确发生。

var emptyEmberObjectClass = Ember.Object.extend({});
var container = Ember.Object.extend({
data: Ember.A([
emptyEmberObjectClass.create({yo:1}),
emptyEmberObjectClass.create({yo:2}),
emptyEmberObjectClass.create({yo:3})
]),
computedData: Ember.computed('data.@each.yo', function(){
var sum = 0;
this.get('data').forEach(function(data){
sum = sum + data.yo;
});
return sum;
}),
test: Ember.observer('computedData', function(){
Ember.$('#a').html('woohoO!');
})
}).create();
var existingItem = container.get('data');
existingItem.objectAt(0).set('yo', 50);

http://jsfiddle.net/stb0nr2y/1/

如您所见,文本字段仍然显示“开始”并且没有更新为“woohoO!”。

任何帮助将不胜感激。

最佳答案

JavaScript:

var emptyEmberObjectClass = Ember.Object.extend({});
var container = Ember.Object.extend({
data: Ember.A([
emptyEmberObjectClass.create({yo:1}),
emptyEmberObjectClass.create({yo:2}),
emptyEmberObjectClass.create({yo:3})
]),
computedData: Ember.computed('data.@each.yo', function(){
var sum = 0;
this.get('data').forEach(function(data){
sum += data.get('yo');
});
return sum;
}),
testObs: Ember.on('init', Ember.observer('computedData', function() {
Ember.$('#a').html('woohoO! cd: `' + this.get('computedData') + '`');
}))
}).create();

var existingItem = container.get('data');
var target = existingItem.objectAt(0);
target.set('yo', 50);

target.set('yo', 100);

正确更新 DOM:

woohoO! cd: 55

然后:

woohoO! cd: 105

请注意,我使用的是 Ember v1.13.10:

<script src="http://builds.emberjs.com/tags/v1.13.10/ember.min.js"></script>

Working demo.

关于javascript - 为什么 Ember 观察者不对数组开火?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32793794/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com