vanthome
vanthome

Reputation: 4926

Cannot access Controller in init function of View in 1.0.0rc

I have a view which is setup by a route plus an associated controller. I can trace that the controller is created but in the init() function of the view, when I do this:

init: function() {                  
  this._super();                     
  console.log(this.get('controller'));
}

The controller is null. If I check in didInsertElement(), the controller is set. I think it would be useful to have the controller in the init() function already. Why is this not the case?

Upvotes: 2

Views: 408

Answers (1)

mavilein
mavilein

Reputation: 11668

This is the case, because init() gets called when the View gets created (= the Ember Object). Somewhere Ember does something similar to the following. Then your init gets called.

var view = Ember.View.create({}); 

At this point the controller is not assigned. The controller is assigned at a later point. Most of the times, this is down by your route. Have a look at this code from the render code for Routes:

function setupView(view, container, options) {
  var defaultView = options.into ? 'view:default' : 'view:toplevel';

  view = view || container.lookup(defaultView); // the view gets created here and init gets called

  if (!get(view, 'templateName')) {
    set(view, 'template', options.template);

    set(view, '_debugTemplateName', options.name);
  }

  set(view, 'renderedName', options.name);
  set(view, 'controller', options.controller); // controller gets assigned to view

  return view;
}

As you can see, at first the view is instantiated and afterwards the controller is assigned to it.

Why does Ember do it that way? Isn't it wrong? Your current understanding is, that there is always a controller connected with your view. But this is not always the case. Think of the {{view}} helper for example. Usually you set it up with a contextBinding. So the 'controller' property is not always set!

What should you do in your case? You did not outline your requirements in detail, but you should be fine using the willInsertElement() hook. This is before the element is in the DOM. That should be early enough to access it, right?

Upvotes: 2

Related Questions