renno
renno

Reputation: 2827

Ember not calling setupController of router

So, I have two paths in my route. I created the two routes as the doc recommends.

My router is the following:

// router.js
Router.map(function() {
  this.route('photos');
  this.route('photo', { path: '/photo/:photo_id' });
});

If I visit firstly the route /photo/ID and then go to /photos, it will only show one object on the latter. (wrong)

If I visit /photos first it shows all the objects and I can go to /photo/ID later on and it will be fine. (right)

I want to make it work both ways. How to do this? You can see my code for each route down below:

// photo.js
export default Ember.Route.extend({
  model(params) {
    return this.get('store').findRecord('photo', params.photo_id);
  }
});

// photos.js
export default Ember.Route.extend({
  setupController(controller, model) {
    let photos = this.get('store').findAll('photo');
    console.log('add all...');
    // convert to an array so I can modify it later
    photos.then(()=> {
      controller.set('photos', photos.toArray());
    });
  },
});

I can always call the findAll() function regardless where the user goes, but I don't think this is smart.

The way I am dealing with the page transitions:

To go to photos I use:

{{#link-to 'photos'}}All{{/link-to}}

To go to /photo/ID I inject the service '-routing' and I use in one event click like this:

routing: Ember.inject.service('-routing'),
actions() {
    selectRow(row) {
        this.get("routing").transitionTo('photo', [row.get('id')]); 
    }
}

Upvotes: 2

Views: 93

Answers (1)

Ember Freak
Ember Freak

Reputation: 12872

findAll will get it from a store and return immediately and later on it will request the server and update the store. but in your case, as you are not using route model hook, so this live array will not be updated so it will not reflect it in the template.

If I visit firstly the route /photo/ID and then go to /photos, it will only show one object on the latter.

In the above case, store will contain only one reocrd, so when you ask for store data using findAll it will return the existing single record.

Another option is,
avoiding this photos.toArray() - It will break live-array update, I am not sure why do you need it here. since photos is DS.RecordArray.

Note: It's important to note that DS.RecordArray is not a JavaScript array, it's an object that implements Ember.Enumerable. This is important because, for example, if you want to retrieve records by index, the [] notation will not work--you'll have to use objectAt(index) instead.

Upvotes: 2

Related Questions