在 ember 路由中对模型使用哈希时未保留模型对象

Model object not preserved when using hash for model in ember route

编辑:我设置了一个实际的 repro of the issue on JSBIN

我已经尝试解决这个问题一段时间了,但我显然不明白模型和 setupController 之间的关系是如何工作的。我有一个模型,它是 returning 散列;两次查找调用的结果:

model(params) {
  return Ember.RSVP.hash({
    course: this.store.find('course', params.course_id),
    topics: this.store.find('topic', { course_id: params.course_id })
  });
},

第一次调用 setupController 时,如果符合预期,model 的值是一个类似于 { course: <Class>, topics: <Class> } 的散列。太棒了,这就是我想要的。

但是,下次调用 setupController 时(例如,转换到另一条路线,然后按浏览器中的后退按钮),model 现在 只是 课程 <Class>:

setupController(controller, model) {
    // when first called model will be { course: <Class>, topics: <Class> }
    // next time entered, model will just be <Class> (just the value of "course" )
    // why is the model object not preserved?
   controller.set('model', model.course);
   controller.set('topics', model.topics);
}}

如果我只是把model()return做成一个资源,每次都是一样的:

model(params) { return this.store.find('course', params.course_id); }
// now `model` will always be "course" in setupController

为什么使用哈希结果没有保留原始模型?我做错了什么吗?

看着它,原来的模型不会被保留,因为在setupController上,你正在调用controller.set('model', model.course)。首次加载时,它会适当地调用 model(params {} 函数,但在后退按钮转换和某些 {{link-to}} 调用时,情况并非总是如此。

在您的 setupController 中,尝试将其更改为 controller.set('course', model.course);,这样您就不会在执行时覆盖您的模型,并且它始终能够找到它。

当您在此处链接时,您正在发送模型 color

{{#link-to 'color' color}}{{color.name}}{{/link-to}}

因此,模型挂钩不是 运行。如果将其更改为 color.id,它将起作用。

提到了here

In the above example, the model hook for PhotoRoute will run with params.photo_id = 5. The model hook for CommentRoute won't run since you supplied a model object for the comment segment. The comment's id will populate the url according to CommentRoute's serialize hook.