Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I chain `get()`s in Ember, or can I use dot notation?

Tags:

ember.js

Should I use:

this.get('controller').get('simpleSearch').get('selectedOptions').get('height')

or

this.get('controller.simpleSearch.selectedOptions.height')

I think the first is... verbose. Is there any reason not to use the second method?

like image 726
Nathan Lutterman Avatar asked Feb 27 '14 02:02

Nathan Lutterman


2 Answers

Can not remember where I read it on the ember site but they suggested the best solution was the dot notation.

this.get('controller.simpleSearch.selectedOptions.height')
like image 131
TrevTheDev Avatar answered Nov 19 '22 11:11

TrevTheDev


While in pursuit of an answer, I found this thread: Definitive guide of when to use .get on discuss.emberjs.com.

According to gordon_kristan's answer:

Always use get(), and use it in one of the following two ways:

// If obj is guaranteed to not be null or undefined
obj.get('very.deep.nested.property');
// If obj might be null or undefined, or if it's not an Ember object,
Ember.get(obj, 'very.deep.nested.property');

Using get() is the only way to ensure that the Ember computed properties will always function properly. For instance, in your example, consider if model was a PromiseObject (which Ember-Data uses quite a bit):

// This will not work, since it won't activate the `unknownProperty` handler on `model`
var startDate = parentView.controller.model.createdAt;
// But this will work
var startDate = Ember.get(parentView, 'controller.model.createdAt');

In addition, as christopher points out:

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.

If you want to read the source, check out ember-metal/lib/property_get.

like image 28
Max Wallace Avatar answered Nov 19 '22 12:11

Max Wallace