jeudi 21 janvier 2016

How to access params in the afterModel hook

I was using an RSVP.hash in my model hook. But I needed my route to load dynamic data based on the url (which contains a dynamic segment). i.e. this.route('foo', {path: ':id'}).

So I decided to move some stuff out, to the afterModel hook instead.

However, I needed to execute the store with params (for pagination):

model(params) {
  this.set('params', params);
  return this.store.findRecord('foo', params.foo_id);
},

afterModel: function(model) {
  console.log(this.get('params')); // logs the right params
  let params = this.get('params');

  // This store query needs access to params
  this.store.query('bar', { filter: { 'foo-id': model.get('id') }, page: { number: (params.page ? params.page : 1) } }).then(bars => {
    this.controller.set('bars', bars);
  });
}

setupController(controller, model) {
  this._super(controller, model);

  this.set('bars', bars);
}

So far I have this, which works:

model(params) {
  this.set('params', params);
  ...
},

afterModel: function(model) {
  console.log(this.get('params')); // logs the right params
  ...
}

But is this the only way to access params in the afterModel hook?

Is this approach sane?




Aucun commentaire:

Enregistrer un commentaire