EmberJS:异步模型

时间:2016-11-04 16:23:55

标签: javascript asynchronous ember.js

@EmberJS 2.6

目前正在做这个

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;
            }
          }
        }
    }
});

问题是,如果呼叫花费太多时间来返回应用程序,那么基本上就是#34;冻结"。我想将这段代码更改为一个异步的代码,渲染页面,并在promise返回时填充:

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

1 个答案:

答案 0 :(得分:1)

如果不深入,您的代码可以改变:

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);

            }
          }
        }
    }
});