Skip to content

Instantly share code, notes, and snippets.

@wycats
Created March 13, 2012 04:03
Show Gist options
  • Select an option

  • Save wycats/2026659 to your computer and use it in GitHub Desktop.

Select an option

Save wycats/2026659 to your computer and use it in GitHub Desktop.
PhoneNumber = Ember.Object.extend({
areaCode: null,
number: null
});
Person = Ember.Object.extend({
areaCode: function() {
var areaCodes = {}, phoneNumbers = this.get('phoneNumber');
for (var i=0, l=phoneNumbers.length; i<l; i++) {
areaCodes[phoneNumbers[i]] = true;
}
return Object.keys(areaCodes);
}.property('[email protected]'),
wifeName: function() {
// how do you tell the difference between this and a call to `name`
// from inside of `wife`
return this.get('wife').get('name');
}.property('wife.name')
});
// The reason this matters is that Ember manages memory in chained
// property observers automatically, which means that, for example,
// if a view is re-rendered, all chained observers, including
// across computed properties, are torn down.
//
// Failing to do this will cause objects to be held onto indefinitely,
// which practically causes significant memory leaks.
@elight
Copy link

elight commented Mar 13, 2012

If areaCode was also an Ember.Object, could you track the dependency when you get() on the areaCode?

WRT second example, get('wife') is being called on the Person object. That could build a dep chain from person -> wife prop -> wife's name prop.

I know, it would still all come back to prewarming.

(and I far prefer discussion here to twitter) :-)

@wycats
Copy link
Author

wycats commented Mar 13, 2012

In the case of the first one, it's not that we're calling get on the areaCode, it's that the dependency is actually on [email protected], which means:

  • it is invalidated whenever an item is added to phoneNumbers
  • it is invalidated whenever an item is removed from phoneNumbers
  • it is invalidated whenever an item already in phoneNumbers has its areaCode property change

In general, the reason you care about using chains is that we automatically manage setting up and tearing down nested observers. If you were to set the phoneNumbers property, not only would we tear down the Array observer, we would also tear down the individual observers on the areaCode property in each phoneNumber.

What I was trying to say about the second example is that just because .get is called while the computed property is being computed doesn't mean it's conceptually a dependency. If it's called inside of the wife, it may just be incidental.

@elight
Copy link

elight commented Mar 13, 2012 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment