1

我有一组汇率用于计算订单对象的价格,我试图找出让这些对象在任何需要的地方可用的最佳方法(模型,基本上只是扁平的 Ember.Objects 和控制器)。

我已经搜索了很多好的解决方案,并且有很多旧的代码示例似乎不再有效,还有很多关于依赖注入的讨论,但没有关于如何使用它的好示例。

所以我采用了这个,感觉有点脏,但是这样我可以在任何需要的地方调用 window.App.exchangeRates :

var ApplicationController = Ember.Controller.extend({
  init: function() {
    this._super();

    var exchangeRates = new ExchangeRates();
    exchangeRates.refresh();

    this.set('exchangeRates', exchangeRates);

    // Expose the exchangeRates to the global scope.
    window.App.exchangeRates = exchangeRates;
  },
});

更具体地说,我需要将它注入到我的模型中,该模型由路由器创建,如下所示:

var BuyBankTransferIndexRoute = Ember.Route.extend({
  setupController: function (controller) {
    controller.set('model', BuyOrder.create({
      type: 'bank_transfer',
    }));
  }
});

然后绑定到模型内部,像这样:

var BuyOrder = Ember.Object.extend({
  init: function () {
    // Whenever the currency data reloads.
    window.App.exchangeRates.addObserver('dataLoaded', function () {
      // Trigger a re-calculation of the btcPrice field.
      this.propertyWillChange('currency');
      this.propertyDidChange('currency');
    }.bind(this));
  },
});

有没有更好的办法?我在这里使用带有 Ember 1.2.0 的 Ember App Kit。

4

1 回答 1

2

我想说你最好的选择是使用控制器的“需求”功能。您的控制器上有一个exchangeRates属性。application比如说,如果你想在posts控制器中拥有那个变量,你可以这样做:

App.PostsController = Ember.Controller.extend({
    needs: ['application'],
    exchangeRates: Ember.computed.alias('controllers.application.exchangeRates')
});
于 2014-01-12T18:15:43.517 回答