Ember访问另一个控制器的数据

时间:2014-11-09 21:38:36

标签: ember.js ember-data

Trucks模型由db支持,可通过rest api访问。 但是,Analysis模型不受db支持,而只是用于客户端的计算。

我需要从Analyzes控制器中访问Trucks数组,但我遇到了2个问题

  1. 需要从数据库中检索卡车数据。如果我立即访问/analyses路由,那么在检查ember控制台时数据存储中没有Trucks。但是,如果我首先访问/trucks,那么我会注意到在数据存储中检索了6条记录。

  2. AnalysesController内部我已经指定了对Trucks的依赖,但是我无法从控制器中访问数据。 http://emberjs.com/guides/controllers/dependencies-between-controllers/显示了如何从模板中进行访问。

  3. 以下是代码

    // router.js
    Classmove.Router.map(function() {
      this.resource('trucks');
      return this.resource('analyses');
    });
    
    Classmove.TrucksRoute = Ember.Route.extend({
      model: function() {
        return this.store.find('truck');
      }
    });
    
    Classmove.Analyses = Ember.Route.extend({
      model: function() {
        return this.store.find('analysis');
      }
    });
    
    
    
    // analyses_controller.js
    Classmove.AnalysesController = Ember.ArrayController.extend({
      needs: ['trucks'],
      trucks: Ember.computed.alias('controllers.trucks'),
      isCalculating: false,
      checkTrucks: function() {
        // I want to access the trucks here
        // I found that I was able to access it like so
        this.get('trucks').model.content 
        // but shouldn't there be a direct way without bypassing Ember
      },
      actions: {
        calculate: function() {
          // does stuff - removed from example for simplicity
        }
      }
    });
    

1 个答案:

答案 0 :(得分:0)

我发现这个答案有用EmberJS: How to load multiple models on the same route?

路由器等待承诺在beforeModelmodelafterModel挂钩上完成。

在我的示例中,afterModel挂钩返回promises的哈希值。在履行承诺后,它会在trucks上设置locationsAnalyzeRoute属性。承诺完成后,调用setupController钩子,我们从AnalyzeRoute读取属性并在控制器上设置它们。

我没有从其他控制器读取数据。我正在从商店中读取数据,因为在调用TrucksController路由之前可能未访问/analyze因此可能未设置其模型属性。

// router.js.coffee
App.AnalyzeRoute = Ember.Route.extend
  model: -> @store.all('location-analysis') # don't fetch from server, checks local store
  afterModel: ->
    Ember.RSVP.hash
      trucks: @store.find('truck').then (trucks) => @set('trucks', trucks)
      locations: @store.find('location').then (locations) => @set('locations', locations)
  setupController: (controller, model) ->
    this._super(controller, model)
    controller.set 'trucks', @get('trucks')
    controller.set 'locations', @get('locations')



// analyze_controller.js
App.AnalyzeController = Ember.ArrayController.extend
  checkTrucks: ->
    trucks = @get('trucks') # returns an Ember Record Array
    # do some checking
  actions:
    calculate: ->
      // does stuff - removed from example for simplicity
相关问题