0
votes

I have been going through Emberjs docs. I came across topic called computed property. I have gone through each and every words there and yet the arguments passed to .property() does not make any sense.

Taking the first example from the doc.

App.Person = Ember.Object.extend({
  // these will be supplied by `create`
  firstName: null,
  lastName: null,

  fullName: function() {
    return this.get('firstName') + ' ' + this.get('lastName');
   }.property('firstName', 'lastName')
  });

  var ironMan = App.Person.create({
  firstName: "Tony",
  lastName:  "Stark"
});

ironMan.get('fullName'); // "Tony Stark"

According to the doc

Notice that the fullName function calls property. This declares the function to be a computed property, and the arguments tell Ember that it depends on the firstName and lastName attributes.

Just to check the significance of arguments passed to .property() I modified them.

fullName: function() {
    return this.get('firstName') + ' ' + this.get('lastName');
   }.property('Captain', 'America')
});

ironMan.get('fullName') returns Tony Stark.

So the final question is, what is the significance of arguments passed to the .property()?

1

1 Answers

2
votes

.property() is a shorter version of Ember.computed(). Elaborating your example

fullName: function() {
    return this.get('firstName') + ' ' + this.get('lastName');
   }.property('firstName', 'lastName')
});

So basically if you don't putup .property() it will be a simple method returning full Name after concatenation. But it gets executed all the time whenever you call the method. But if you add .property() [basically a computed property], value gets cached and avoid multiple executions.

If there is a change in firstName or lastName, you might want to update the fullName value in cache. Thats why we pass arguments inside .property() as .property('firstName', 'lastName') . This is basically concept of observers. So basically in 2nd code you written, you might think its working properly but when there is change in firstName or lastName, fullName won't get changed coz it is observing variables named Captain, America rather firstName, lastName.