简体   繁体   中英

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

EDIT: I've set up an actual repro of the issue on JSBIN

Been trying to resolve this for a while now and I'm clearly not understanding how the relationship between model and setupController works. I have a model which is returning a hash; the result of two find calls:

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

The first time setupController gets called, the value of model if as expected, a hash like { course: <Class>, topics: <Class> } . Awesome, that's what I want.

However, the next time setupController gets called (for example, transition to another route and then press the back button in the browser), the model is now just the course <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);
}}

If I just make model() return a single resource, it's the same every time:

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

Why is the original model not preserved when using a hash result? Am I doing something wrong?

You're sending the model color when you're linking here:

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

Because of that, the model hooks aren't run. If you change that to color.id, it'll work.

It's mentioned 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.

Looking at it, the original model will not be preserved because on setupController, you are calling controller.set('model', model.course). When it first loads, its called the model(params {} function appropriately, but on back button transitions and certain {{link-to}} calls, that isn't always the case.

In your setupController, try changing it to controller.set('course', model.course); , that way you aren't overwriting your model on execution as well and it will always be able to find it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM