Skip to content

Instantly share code, notes, and snippets.

@schickm
Last active September 24, 2017 21:33
Show Gist options
  • Save schickm/08ec48667a4d43e59d91 to your computer and use it in GitHub Desktop.
Save schickm/08ec48667a4d43e59d91 to your computer and use it in GitHub Desktop.
Ember Dynamic aliases
import Ember from 'ember';
export default Ember.Object.extend({
model: null,
subpath: null,
dynamicModelProperty: Ember.computed('model', 'subpath', function() {
let subpath = this.get('subpath');
if ( subpath ) {
let DynamicClass = Ember.Object.extend({
value: Ember.computed.alias(`model.${subpath}`)
});
return DynamicClass.create({model: this.get('model')});
} else {
return Ember.Object.create({});
}
}),
value: Ember.computed.alias('dynamicModelProperty.value'),
});
@mwadden
Copy link

mwadden commented May 4, 2016

AMAZING. Thank you! I killed the better part of a day trying to figure out a solution for this.

@rewritten
Copy link

rewritten commented Oct 29, 2016

There is a probably simpler way, just replacing the computed alias whenever the subpath changes:

export default Ember.Component.extend({
  subpathObserver: Ember.observer('subpath', function(){
    this.value = Ember.computed.alias(`model.${this.get('subpath')}`)
    this.notifyPropertyChange('value');
  }).on('init')
});

@sukima
Copy link

sukima commented Dec 17, 2016

@rewritten Your suggestion uses observers which (by nature) rely on side-effects. This can make code harder to reason about then simplifying the syntax. It also means that the computed property in question (value) is no longer lazy evaluated and you loos the performance benefits of the Ember run loop.

In general observers are an anti pattern. @schickm's original use of a computed proxy object may seem a bit more verbose but it doesn't suffer the negative impact that an observer would introduce.

DockYard has a nice post about observers: https://dockyard.com/blog/2015/11/16/best-practices-functional-programming-and-the-observer-effect

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