Rentonie
Rentonie

Reputation: 477

EmberJS : Async Model

@EmberJS 2.6

Currently im doing this

import Ember from 'ember';

export default Ember.Route.extend({

  model: function() {
        ...
        var ajax_response = Ember.$.ajax(url, {
          "type": 'POST',
          "async": false,
          "headers": {
            "Authorization": _auth_header
          },
          "data": JSON.stringify(data),
          "contentType": "application/json"
        });
        if (ajax_response.hasOwnProperty("responseJSON")) {
          var response = ajax_response.responseJSON;

          if (response.hasOwnProperty("status") && response.status === success_status) {
            response = response.result;

            if (typeof response === "object") {
                return response;
            }
          }
        }
    }
});

Problem is, that if the call takes too much time to return the app is essentially "frozen". I want to change this piece of code to a working async one, having the page rendered, and when the promise returns to populate the :

{{#each model as |transaction|}}
....

Upvotes: 0

Views: 212

Answers (1)

If not going deep, your code can be altered so:

import Ember from 'ember';

export default Ember.Route.extend({

  model: function() {
     return [];
  },
  setupController: function(controller, model) {
        controller.set('model',model);

        //here you can fire loader in template based on isLoading in controller;
        controller.set('isLoading',true);

        ...
        var ajax_response = Ember.$.ajax(url, {
          "type": 'POST',
          "async": false,
          "headers": {
            "Authorization": _auth_header
          },
          "data": JSON.stringify(data),
          "contentType": "application/json"
        });
        if (ajax_response.hasOwnProperty("responseJSON")) {
          var response = ajax_response.responseJSON;

          if (response.hasOwnProperty("status") && response.status === success_status) {
            response = response.result;

            if (typeof response === "object") {
                controller.set('isLoading',false);
                controller.get('model').pushObjects(response);

            }
          }
        }
    }
});

Upvotes: 1

Related Questions