我在the ember.js homepage上找到了指南,并在this section找到了代码:
Person.reopen({
lastNameChanged: function() {
// The observer depends on lastName and so does fullName. Because observers
// are synchronous, when this function is called the value of fullName is
// not updated yet so this will log the old value of fullName
console.log(this.get('fullName'));
}.observes('lastName')
});
根据评论,函数lastNameChanged
应该输出旧版本的fullName属性。但是当我运行稍微修改过的代码时,我得到了新版本的属性:
Person = Ember.Object.extend({
firstName: null,
lastName: null,
fullName: function() {
return this.get('firstName') + ' ' + this.get('lastName');
}.property('firstName', 'lastName'),
});
Person.reopen({
lastNameChanged: function() {
console.log('lastName changed. Name is now: ' + this.get('fullName'));
}.observes('lastName')
})
max = Person.create({
firstName: 'Max',
lastName: 'Lehmann',
});
max.set('lastName', 'Mustermann');
console.log(max.get('fullName'));
我知道该指南是基于旧版本的Emberjs(我想1.3)。我用当前版本的Ember(1.6.1)测试了代码。新版本是否解释了该行为的变化?
答案 0 :(得分:1)
更改值后会触发观察者。 fullname是一个计算属性,只有在您尝试访问它时才会执行。当您访问它时,在obeserver中,lastname已经更改,因此fullname将给出新值。要获得先前的值,我们使用之前的观察者。
使用observesBefore('lastName')
代替observes('lastName')