Can you set an Ember.computed.alias dynamically?

I’m creating this component here that requires me to set “needs” and some computed aliases dynamically:

Spark.SubmitFormComponent = Ember.Component.extend({
  setup : function() {
    var type = this.get("type");
    this.setProperties({
	needs : [type+"List", type],
	fields : Ember.computed.alias("controllers."+type+"List.fields"),
	layouts: Ember.computed.alias("controllers."+type+"List.layouts"),
	isEditing: Ember.computed.alias("controllers."+type+".isEditing"),
	data : Ember.computed.alias("controllers."+type+".model")
    });
 }.on("init"),
})

Now when I call get on one of these properties this.get("fields") I get a ComputedProperty object instead of the value of the controller I’m trying to reference. Is this the expected behaviour and if so how can I get the value I want?

Close, what you want is Ember.defineProperty.

Ember.defineProperty(this, 'fields', Ember.computed.alias("controllers."+type+"List.fields"));

Should do what you’re looking for.

1 Like

This doesn’t seem to work either.

Is it possible that you can’t set an Ember.computed.alias inside a component?

That should work, maybe try it in the actual init: function rather than a function with .on(‘init’)

init runs a little sooner in the initialization process.

App.MyThing = Em.Model.extend({
  bar: 'baz',
  init: function() {
    Em.defineProperty(this, 'foo', Em.computed.alias('bar'));
  }
});

App.MyThing.create().get('foo');  // should be 'baz'

More info here: http://www.thesoftwaresimpleton.com/blog/2013/08/11/dyanamic-cp/

I’ve created a utility function for this:

https://gist.github.com/pwfisher/283716ad9898c7fc8101

Here’s a quick example:

var obj = Ember.Object.create();
obj.set('a', 'yay'); // your initial property
Ember.defineProperty(obj, 'b', Ember.computed.alias('a')); // your alias
obj.get('b'); // => "yay"