2014-01-12 25 views
1

我有一組匯率用於計算訂單對象的價格,我試圖找出使這些數據可用的最佳方法他們需要(模型,基本上只是平坦的Ember.Objects和控制器)。我如何在我的Ember應用程序中發佈全球數據1.0

我已經搜索了很多很好的解決方案,還有很多舊的代碼示例不再有效,以及大量關於依賴注入的討論,但沒有關於如何使用它的好例子。

所以我使出這個,感覺有點髒,但這樣一來,我可以打電話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; 
    }, 
}); 

更specificly,我需要它注入到我的模型,其由路由器這樣創建的:

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。

回答

2

我會說你最好的選擇是使用控制器的'needs'功能。您的application控制器上有exchangeRates財產。如果你想,說,有一個posts控制變量,你可以這樣做:

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

使用此別名會小得多,'exchangeRates:Ember.computed.alias('controllers.application.exchangeRates ')' – Kingpin2k

+1

我其實剛剛讀過別名。 :)我現在就更新它。 – GJK

+0

是的,這將使它在該控制器中可用,但是如何將其放入我的模型中,這些模型通常由路徑加載? – mikl

相關問題