Search code examples
javascriptember.jsroutesember-cli

Updating template when route model changes (?)


import Ember from 'ember';

export default Ember.Route.extend({
logMore: 20,
dateEncode: "",
model: function(){
 var url = "https://xxxx/api/xxxx";
 var localData = JSON.parse(localStorage.getItem("user"));
 var data = { auth_token: localData.user_token };

 ( this.get('dateEncode') !== "" )? url += "?from="+ this.get('dateEncode') : url;
 return Ember.$.ajax({ 
   url: url,
   headers: { "X-Api-Token": data.auth_token } 
 }).then(function(data) { 
   console.log(data);
   return data;
   });
 }.observes('dateEncode'),
 actions: {
   loadMore: function(){
      var today = new Date();
      today.setDate(today.getDate() - this.get('logMore'));
      var initial = this.get('logMore') + 10;
      this.set('logMore', initial);
    this.set('dateEncode', today.toISOString());
   }
  }
});

I am using ajax to call an API and made an action than change the url with a param 'from' it's a date return some days ago, the modal can call and return the new data but the template no change, i don't know how to do it, if there somebody who can help thanks for your time.

Maybe another way to do that (?)


Solution

  • The issue here is that you are misusing the model hook. The route's model hook is called only if the route was not already supplied a model in order to generate a model for the controller.

    The observer you add to the function won't change model on the controller.

    I would suggest extending your controller to handle this action (instead of sending it to the route) and handling the loadMore logic there.

    import Ember from "ember";
    
    export Ember.Controller.extend({
    
      actions: {
        loadMore: function () {
          var model = this.get('model');
          Ember.$.ajax({ /* add params */ })
            .then(function(data) { model.addObjects(data); });
        }
      }
    

    });