How do I make data globally available in my Ember Application post 1.0

467 Views Asked by At

I have a set of exchange rates that are being used to calculate prices on order objects, and I'm trying to figure out the best way to make these available whereever they're needed (Models, basically just flat Ember.Objects, and Controllers).

I've searched a lot for a good solution, and there's a lot of old code examples that no longer seem to work, as well as a lot of talk about dependency injection, but no good examples on how to use it.

So I've resorted to this, which feels kinda dirty, but this way I can call window.App.exchangeRates whereever I need it:

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

More specificly, I need it injected into my Model, which is created by the Router like this:

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

And then bound inside the model, like this:

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

Is there a better way? I'm using Ember App Kit with Ember 1.2.0 here.

1

There are 1 best solutions below

3
On

I would say your best bet is to use the 'needs' functionality of controllers. You have a exchangeRates property on your application controller. If you wanted to, say, have that variable in a posts controller, you could do this:

App.PostsController = Ember.Controller.extend({
    needs: ['application'],
    exchangeRates: Ember.computed.alias('controllers.application.exchangeRates')
});