0

我正在调用服务器以通过 ajax 请求获取一些数据,并且我使用了一个承诺。虽然我的模板会在数据返回后自动更新,但我很不幸地访问了控制器中的数据,因为我不知道它的确切时间。

为了解决这个问题,我可以在控制器中进行额外的 ajax 调用以获取相同的数据,但这感觉很难看。有没有更好的方法来知道何时访问控制器中的数据?作为一种解决方法,我尝试调用需要数据的函数,didInsertElement但这并没有解决它。

App.ActiveDataSet = Ember.Object.extend({
  progress: 0
});

App.ActiveDataSet.reopenClass({
  findAll: function(project_id) {
    var result = [];
    $.ajax({
      url: '/active_data_sets.json',
      type: 'GET',
      data: {'project_id': project_id}
    }).then(function(response) {
        response.active_data_sets.forEach(function(newset) {
          result.addObject(App.ActiveDataSet.create(newset));
        });
    });

    return result;
  }
});

App.MapviewShowRoute = Ember.Route.extend({
  setupController: function(controller, model) {
    this.controllerFor('activedatasetIndex').set('content', App.ActiveDataSet.findAll(model.id));
  }
});

App.MapviewShowController = Ember.ObjectController.extend({
  needs: ['activedatasetIndex'],

  content: null,
  dataSets: [],

  createDataSets: function() {

    // create the datasets
    for (var counter = 0; counter < this.get('controllers.activedatasetIndex.content').length; counter++) {
      alert(dataSets[counter].ds.name);
    }
  }

});

App.MapviewShowView = Ember.View.extend({
  map: null,

  didInsertElement: function() {
    var map = null;

    var myOptions = {
      zoom: 8,
      center: new google.maps.LatLng(52.368892, 4.875183),
      mapTypeControl: true,
      mapTypeControlOptions: {
        style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
      },
      navigationControl: true,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(this.$('#map_canvas').get(0), myOptions);


    this.set('map', map); //save for future updations

    var h = $(window).height(),
        offsetTop = 60; // Calculate the top offset

    $('#map_canvas').css('height', (h - offsetTop));

    // get the datasets
    this.controller.createDataSets();
  }
});
4

1 回答 1

0

您是否尝试过继续承诺链:

App.ActiveDataSet.reopenClass({
  findAll: function(project_id) {
    return $.ajax({
      url: '/active_data_sets.json',
      type: 'GET',
      data: {'project_id': project_id}
    }).then(function(response) {
        var result = [];
        response.active_data_sets.forEach(function(newset) {
          result.addObject(App.ActiveDataSet.create(newset));
        });
        return result;
    });
  }
});

App.MapviewShowRoute = Ember.Route.extend({
  setupController: function(controller, model) {
    App.ActiveDataSet.findAll(model.id).then(function(content) {
      this.controllerFor('activedatasetIndex').set('content', content);
    });
  }
});
于 2013-04-07T13:11:08.953 回答