gpt4 book ai didi

javascript - Ember.js 中的观察者和异步

转载 作者:行者123 更新时间:2023-12-03 12:12:43 24 4
gpt4 key购买 nike

我按照 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) 测试了代码。新版本是否解释了该行为的变化?

最佳答案

观察者在值改变后被触发。 fullname 是一个计算属性,仅当您尝试访问它时才会执行。当您访问它时,在观察服务器内,姓氏已经更改,因此全名将给出新值。为了获取之前的值,我们使用之前的观察者。

使用observesBefore('lastName')代替observes('lastName')

关于javascript - Ember.js 中的观察者和异步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24884925/

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