【问题标题】:Ember access data of another controllerEmber 访问另一个控制器的数据
【发布时间】:2014-11-25 08:38:59
【问题描述】:

Trucks 模型由 db 支持,并可通过 rest api 访问。 然而,分析模型不受数据库支持,而只是用于客户端的计算。

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

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

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

下面是代码

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

【问题讨论】:

  • 您应该使用 get 方法来访问属性。而不是this.get('trucks').model.content 使用this.get('trucks.model') 并且不要忘记checkTrucks 方法上的observes('trucks.model)

标签: ember.js ember-data


【解决方案1】:

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

路由器在 beforeModelmodelafterModel 钩子上等待 Promise 完成。

在我的示例中,afterModel 钩子返回一个承诺的哈希值。当承诺被履行时,它会在AnalyzeRoute 上设置truckslocations 属性。一旦 promise 完成,就会调用 setupController 钩子,我们从 AnalyzeRoute 读取属性并将它们设置在控制器上。

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

// 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

【讨论】:

    猜你喜欢
    • 2018-06-15
    • 1970-01-01
    • 1970-01-01
    • 2014-11-07
    • 1970-01-01
    • 2016-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多