来自路径 returns 的 EmberJS 模型在控制器中未定义

EmberJS model from route returns undefined in controller

有人可以帮我解决以下问题吗?

我使用的是 EmberJS 3.4 版本,我有一条路线看起来像

export default Route.extend({
model(){
    const items = [{price: 10}, {price: 15}]
    return items
 },
});

和一个 returns 未定义模型

的控制器
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

出于某种原因,this.model returns 未定义,但是当我记录“this”时,它具有模型对象作为 属性 列出。

我的问题是,当我在计算的 属性 中访问模型时,为什么 属性 不是未定义的?

导出默认值 Controller.extend({

subtotal: computed('this.model', function(){
     return  this.model.reduce((acc, item) => {
         return acc + item.price
     },0) // return 25
    }),
 })

控制器是单例,因此您无法访问 init 中的模型。

when I access model within a computed property why the property isn't undefined ?

访问计算属性(以及更现代的 ember 原生 getter)是对 model 属性 进行反应式访问的唯一方法。这种“反应性”使您的所有数据保持同步——并且在 ember 3.4 中,在依赖关系也得到解决之前不会调用计算的回调。

更多信息

For some reason, this.model returns undefined but when I log "this", it has the model object as the property listed.

发生这种情况是因为您记录了一个 object,并且控制台中的对象没有 复制 到控制台,引用被呈现,所以如果您没有速度够快,到你查看的时候,数据就全部解决/结算了。