Javascript Ember.js中的观察者和异步
我按照上的指南进行操作,发现代码位于: 根据注释,函数Javascript Ember.js中的观察者和异步,javascript,ember.js,Javascript,Ember.js,我按照上的指南进行操作,发现代码位于: 根据注释,函数lastNameChanged应输出fullName属性的旧版本。但当我运行稍微修改过的代码时,我得到了新版本的属性: Person = Ember.Object.extend({ firstName: null, lastName: null, fullName: function() { return this.get('firstName') + ' ' + this.get('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)测试了代码。新版本是否解释了该行为的变化?在a值发生变化后,会触发观察者。fullname是一个计算属性,仅在您尝试访问它时执行。当您在obeserver中访问它时,lastname已经更改,因此fullname将给出新值。为了得到之前的值,我们使用before观察器
使用
observesBefore('lastName')
代替observes('lastName')
试试observesBefore('lastName')代替observes('lastName')太好了,谢谢!现在,它会在更新之前显示名称。你知道这是否是由新版本的灰烬造成的吗?我不知道以前的版本是怎么回事。值更改后,将触发观察者。fullname是一个计算属性,仅在您尝试访问它时执行。当您在obeserver中访问它时,lastname已经更改,因此fullname将给出新值。为了得到之前的值,我们使用before观察器。好的,非常感谢。请下次回答这个问题,这样我就可以将此线程标记为已解决。自1.0.0以来,此行为适用于所有版本。我没有测试早期版本。
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'));