Reputation: 637
I follewed the guide on the ember.js homepage and found that code at 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')
});
According to the comments the function lastNameChanged
should output an old version of the fullName property. But when I ran my slightly modifed code I got the new version of the property:
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'));
I know that the guide is based on an older version of Emberjs (I suppose 1.3). I tested the code with the current version of Ember (1.6.1). Does the new version explain the change in that behaviour?
Upvotes: 0
Views: 128
Reputation: 31779
Observers are fired after a a value is changed. fullname is a computed property and only gets executed when you try to access it. When you access it, inside the obeserver, lastname is already changed hence fullname will give the new value. To get the previous value we use the before observer.
Use observesBefore('lastName')
instead of observes('lastName')
Upvotes: 1