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

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

本文关键字:模型 哈希时 对象 保留 ember 路由      更新时间:2023-09-26

编辑:我已经在JSBIN上设置了这个问题的实际再现

一直试图解决这个问题一段时间了,我显然不理解模型和setupController之间的关系是如何工作的。我有一个返回哈希值的模型;两个find调用的结果:

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()返回单个资源,它每次都是相同的:

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

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

当你链接到这里时,你正在发送模型color:

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

因此,模型钩子不会运行。如果你把它换成颜色。我,会成功的。

这里有提到。

在上面的例子中,PhotoRoute的模型钩子将运行参数个数。Photo_id = 5。此后,CommentRoute的模型钩子将不再运行您为注释段提供了一个模型对象。评论的id将根据CommentRoute的序列化钩子填充url。

查看它,原始模型将不会被保留,因为在setupController上,您正在调用controller。设置("模型",model.course)。当它第一次加载时,它被适当地称为model(params {}函数,但在后退按钮转换和某些{{link-to}}调用时,情况并非总是如此。

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