2014-04-03 21 views
0

我有一個Message模型,其中valueauthor屬性。我能做到這一點灰燼碼(控制器,模型,視圖等)內:如何使用Emberjs將對象推送到全局`Store`

this.store.push('message', msgObj) 

但是,以下在全球範圍內不工作,說把裏面<script src="websocket_processor.js">像:

msgObj = {value: 'Hello!', author: 'Jules'} 
//I've tried the following but does not work 
this.store.push('message', msgObj) //`this` doesn't point to ember 
store.push('message', msgObj) //Console error: undefined store 
App.Store.push('message', msgObj) //Uncaught TypeError: Object function() {if (!wasApplied) {... 

我想這是外界的餘燼,因爲我使用websocket-rails寶石從我現在使用下面的函數

dispatcher.bind('add_message', function(data) { //add_message is just a method param from server 
    //Code where I need to use Ember to store say 
    this.store.push('message', data) 
} 

我堅持這個好幾個小時。任何幫助,將不勝感激。謝謝!

+0

如何將數據存儲在localStorage中?即'localStorage.message = msgObj'或類似的東西。 – EmptyArsenal

回答

1

您可以使用應用程序初始值設定程序執行作業並在註冊後查找存儲區,以便您可以在外部組件中使用它。

Ember.onLoad('Ember.Application', function (Application) { 
    Application.initializer({ 
     name: "websocket-rails", 
     after: "store", 

     initialize: function (container, application) { 
      var store = container.lookup('store:main'); 
      // Now you can inject store to component outside of Ember 
     } 
    }); 
}); 
+0

太棒了!謝謝! –