如何使用Emberjs将对象全局推送到“Store”

时间:2014-04-03 15:44:30

标签: ruby-on-rails ember.js websocket

我的Message模型具有valueauthor属性。我可以在Ember代码(控制器,模型,视图等)中执行此操作:

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 gem,我使用以下函数

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

我现在已经坚持了几个小时。任何帮助,将不胜感激。谢谢!

1 个答案:

答案 0 :(得分: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
        }
    });
});