Can you set "needs" inside init of controller?

I have a generic controller with a generic “parent” ArrayController that changes depending on it’s type.

The child is rendered using {{outlet}} so I can’t use “parentView” as my reference.

I need to set the needs property of the child to the parent but the name can’t be hardcoded as it changes depending on the type.

I so far haven’t been able to get the name and set “needs” inside the init function of the child.

I don’t think so, because it appears the value of needs is handled completely during Em.Controller.init (src). The code is confusing at first glance so you could still test it to be sure.

It would be interesting if the needs property were observed, but I think it is intended to be declarative and explicitly list dependencies in the source code itself.

I think it should work if you handle it via an event listener, like .on(‘init’). Let me check a js bin real quick.

Kinda like this? http://emberjs.jsbin.com/sorayi/1/

If you really need to do this dynamically, I would grab the controller you need from the container directly. For example,

collaboratingController: function(){
  var controllerName = yourLogicToDetermineControllerName();
  return this.container.lookup('controller:' + controllerName);
}.property()

Note that using the container this way is considered private API, and might break in future versions of Ember, so use at your own risk.

1 Like