Can some one help me on the below doubt?
I am using EmberJS 3.4 version and I have a route which looks like
export default Route.extend({
model(){
const items = [{price: 10}, {price: 15}]
return items
},
});
and a controller which returns undefined for model
export default Controller.extend({
init(){
console.log(this.model); //returns undefined
console.log(this); //has the model object as a property
},
})
see this image which contains output
For some reason, this.model returns undefined but when I log "this", it has the model object as the property listed.
My question is, when I access model within a computed property why the property isn't undefined ?
export default Controller.extend({
subtotal: computed('this.model', function(){
return this.model.reduce((acc, item) => {
return acc item.price
},0) // return 25
}),
})
CodePudding user response:
Controllers are singletons, so you can't access the model in init
.
when I access model within a computed property why the property isn't undefined ?
Accessing in computed properties (and in more modern ember, native getters) is the only way to have a reactive access to the model
property. This "reactiveness" keeps all your data in sync -- and in ember 3.4, computeds' callbacks are not invoked until the dependencies are also resolved).
More information
- about controllers: https://guides.emberjs.com/release/routing/controllers/#toc_where-and-when-to-use-controllers (current docs (4.3 at the time of writing))
- about computed properties: https://guides.emberjs.com/v3.4.0/object-model/computed-properties/#toc_computed-properties-only-recompute-when-they-are-consumed (docs from 3.4)
For some reason, this.model returns undefined but when I log "this", it has the model object as the property listed.
this happens because you log an object
, and objects in the console are not copied to the console, the reference is rendered, so if you're not fast enough, the data will all be resolved / settled by the time you view it.