I have a strange behavior with my Ember app. I can't make any sense out of it.
Basically I'm using Ember octane and I wanted to access my model from my route
to my controller
.
This is my route
import Route from '@ember/routing/route';
export default class ChatIndexRoute extends Route {
model() {
return {
chatMessages: [
{
username: '1',
message: 'Hi',
read: true,
},
{
username: '1',
message: 'how are you?',
read: false,
},
{
username: '1',
message: 'its been a long time :)',
read: false,
},
],
};
}
setupController(controller, model) {
controller.set('model', model.chatMessages);
}
}
and this is my controller
import Controller from '@ember/controller';
export default class ChatIndexController extends Controller {
init() {
super.init(...arguments);
console.log('test', this.model);
}
}
When I console.log(this.model)
I got undefined
.
But when I simply do a console.log(this)
I got a whole object with a model property filled with chatmessages
This is crazy
This is just a little timing confusion.
init()
on the controller is executed beforesetupController
on the route. sothis.model
isundefined
.But when you do
console.log(this)
you get the complete controller logged. And the magic of the console is that it is live. So when this object later (not much later, just a tiny little bit) will be updated, you will see it in the console. And so you can inspect themodel
property on the controller in the console, even if it wasnt there when you logged the controller.