Ember 从其他地方访问的控制器数据

Ember Controller Data Accessed From Other Places

我有一个 websocket 连接,在我的 application.js 控制器中获取实时价格数据。我把它放在这里是因为我希望初始化连接并从任何页面访问数据,而不是在每次加载页面时都重新连接。

我不知道如何从其他控制器或模板访问这些数据。

我想做的两件事: 1) 检查一个值并更新导航栏中每个页面上的动态价格。 2)访问其他控制器中的websocket数据。我不知道这是否会影响已经在 application.js 中定义的消息处理程序。我想事件数据应该进入一个变量。

application.js

headerPrice: 0,

setupWebsocket: function() {
  this._super();
  var socket = this.get('websockets').socketFor('ws://localhost:7000/');
  socket.on('open', this.myOpenHandler, this);
  socket.on('message', this.myMessageHandler, this);
  socket.on('close', function(event) {
    console.log('Websocket closed');
  }, this);
}.on('init'),

myOpenHandler: function(event) {
  console.log('Websocket Opened: ' + JSON.stringify(event));
},

myMessageHandler: function(event) {
  if (event.data == "foo") {
     this.headerPrice = event.data.price;
  };
}

}

以初始值设定项和服务扩展结束(ember-websocket 已经是一项服务)。

初始化程序:

export function initialize(app) {
  app.register('websocket:main', 'websocket', { instantiate: true, singleton: true });
  app.inject('controller', 'websocket', 'service:websocket');
  app.inject('component', 'websocket', 'service:websocket');
}

export default {
  name: 'websocket',
  initialize: initialize
};

服务:

import websocket from 'ember-websockets/services/websockets';

export default websocket.extend({
  init: function() {
    this._super.apply(this, arguments);

    var socket = this.socketFor('ws://localhost:7000', ['echo-protocol']);
    console.log('initializing websocket...');
    socket.on('open', this.myOpenHandler, this);
    socket.on('message', this.myMessageHandler, this);
    .....