Definitive guide of when to use .get

@gordan_kristan is right on. Always use get() and set() as opposed to accessing the properties directly. And yes, deeply nested properties should be accessed using obj.get('very.deeply.nested.property'). This way, your code adheres to the Uniform Access Principle. The code that reads the property does not need to worry about whether the property is computed, whether unknownProperty is being used in the chain, whether the property is being observed, or how ember-metal otherwise decides to handle the property. Ember’s philosophy is that these are internal details that should not be of concern to the object reading the property, so just use the get() / set() conventions at all times and you’ll be happy and productive.

Using obj.get('very.deeply.nested.property') will only throw an undefined error if obj is undefined. If any other property in the chain is undefined, then the call to get() will simply return undefined. If instead you called get() at every level, then it would throw an error if any level was undefined.

Another common pattern in Ember is to define an aliased property on the class that is consuming the property:

startDate: Ember.computed.alias('parentView.controller.model.createdAt')

This way, you can just call this.get('startDate') to read the value. This will keep your code DRY, and observers on startDate will work as well.

2 Likes