Search code examples
ember.jsember-dataember-cli

emberjs resetting a routes model


I want to reset a model on a route after a user clicks the sort header on a table:

import Ember from 'ember';
//import _ from 'lodash';

export default Ember.Route.extend({
    needs: 'event-profile',
    model: function(){
        var parentmodel = this.modelFor('eventProfile').get('slug');
        return this.store.find('listingEvent', { eventInstanceSlug: parentmodel, skip: 0, limit: 20 });
  },
  actions: {
        orderByStart: function(){
            this.set('loading', true);
            console.debug('order by start');
            var _this = this;
            var parentmodel = this.modelFor('eventProfile').get('slug');
            this.store.find('listingEvent', { eventInstanceSlug: parentmodel, skip: 0, limit: 20, sort: 'start' })
            .then(function(model){
                _this.set('loading', false);
                _this.set('model', model);
            });
        }
     }
});

orderByStart is getting fired and i can see the correct data is being returned but setting the model with _this.set('model', model); doesn't seem to have any effect?

What is the proper way to go about this?


Solution

  • The underlying issue is that your action handler is on your route but the model property you need to change is on your controller. The fast change is to call controllerFor.

    e.g. this: _this.set('model', model);

    becomes: _this.controllerFor('my-route').set('model', model);

    However, this could be better done by moving your action handler to the controller itself.

    import Ember from 'ember';
    
    export default Ember.Controller.extend({
      needs: 'event-profile',
    
      loading : false,
    
      actions: {
        orderByStart: function(){
    
          this.set('loading', true);
          var _this = this;
          var parentmodel = this.get('controllers.eventProfile.model.slug');
    
          this.store.find('listingEvent', { eventInstanceSlug: parentmodel, skip: 0, limit: 20, sort: 'start' })
            .then(function(model){
              _this.setProperties({ loading : false, model : model});
            });
          }
       }
    });