Can you set an Ember.computed.alias dynamically?


#1

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?


#2

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.


#3

This doesn’t seem to work either.


#4

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


#5

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/


#6

I’ve created a utility function for this:


#7

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"