5

I can't seem to get the model from inside the controller, even though the controller seems to have a model property set. The following:

export default Ember.ObjectController.extend({
    init: function() {
        this._super();
        console.log(this.get('model'));
        console.log(this.model);
        console.log(this);
    }
}

prints out:

enter image description here

Any ideas?

Felix
  • 3,783
  • 5
  • 34
  • 53

2 Answers2

4

So it turns out that when I examine the model by setting a break point it is empty. I assume the console shows content because it updates the model once the content arrives.

In init() the model is unreachable:

init: function() {
    this._super();
    console.log(this.get('model'));  // null
}

Same for any method .on('init'):

onInit: function() {
    console.log(this.get('model'));  // null
}.on('init'),

But the model is accessible to actions (I'm assuming because the model has been set up by the time the action is called):

someAction: function() {
    console.log(this.get('model'));  // model object as expected
}

So to answer my question, this.get('model') can be used to access the model from the controller, but just not in init() or .on('init') methods.

Felix
  • 3,783
  • 5
  • 34
  • 53
3

The an Ember.ObjectController is a proxy for the model. So the model can be referenced using this as you found in your example. So then in a template {{this.aModelAttr}} or just {{aModelAttr}}. Like you question suggests it's a bit confusing.

The ObjectController is being deprecated as of Ember 1.11.0. So to simplify use Ember.Controller and in your controller you can reference the model by this.get('model')

Then in the template use {{model.aModelAttr}}

To give the model a domain specific ie: books or user name use

export default Ember.Controller.extend({
    domainSpecificName: Ember.computed.alias('model')
}

Then in your templates you can use {{domainSpecificName.aModelAttr}}

kiwiupover
  • 1,782
  • 12
  • 26
  • Awesome, I'll give this a go first thing in the morning! – Felix Apr 21 '15 at 06:55
  • So it looks like my problem was something else (see my answer below), but I'll accept this because it cleared things up for me and pointed me in the right direction. Cheers for the help! – Felix Apr 21 '15 at 22:22