EmberJS全局websocket连接

EmberJS全局websocket连接

本文介绍了EmberJS全局websocket连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用EmberJS和im尝试从后端使用websocket(socket.io)获取数据,所以我设置了这个应用程序路由

  App.ApplicationRoute = Ember.Route.extend(
setupController:(controller,data) - >
store = @get'store'
socket = io.connecthttp :// localhost:4000 / orders## Line 4
socket.onnew_order,(order) - >
store.load(App.Order,order)
套接字。 onnew_billing,(bill) - >
store.load(App.Bill,bill)
socket.onconnected, - >
console.logReady
模型: - >
return {title:Ordenes}
actions:
markAsDone:(type,type_id) - >
#将值发送给后端
socket.emitconfirm_+类型,##行16
id:type_id
#通过id
查找记录如果type ==order
record = App .Order.find(type_id)
transition =orders
else如果type ==bill
record = App.Bill.find(type_id)
transition =bill
#从商店中删除
record.then((r) - >
r.deleteRecord()

#显示记录类型列表
@transitionTo(transition)

/ pre>

在第4行正在设置连接,当我点击/时正在获取对象,但在我进入路由/ orders对象不是被取出,并且在上面的代码中的第16行,我不能使用套接字变量

 未捕获ReferenceError:未定义套接字

有更好的方法来管理这个吗?

解决方案

所以使用可重复使用的套接字的正确方法是将其设置在商店内

  App.Store = DS.Store.extend(
修订版本:12
适配器:适配器
套接字:io.connecthttp:// localhost:4000 / orders

所以我可以使用

$ b在代码的任何部分访问它
$ b

  socket = @get'store.socket'


Im using EmberJS and im trying to get data from the backend using websocket (socket.io) so i've set this Application Route

  App.ApplicationRoute = Ember.Route.extend(
  setupController: (controller, data) ->
    store  = @get 'store'
    socket = io.connect "http://localhost:4000/orders" ## Line 4
    socket.on "new_order", (order) ->
      store.load(App.Order, order)
    socket.on "new_billing", (bill) ->
      store.load(App.Bill, bill)
    socket.on "connected", ->
      console.log "Ready"
  model: ->
    return { title: "Ordenes" }
  actions:
    markAsDone: (type, type_id) ->
      # Send value to backend
      socket.emit "confirm_" + type,                    ## Line 16
        id: type_id
      # Find record by id
      if type == "order"
        record = App.Order.find(type_id)
        transition = "orders"
      else if type == "bill"
        record = App.Bill.find(type_id)
        transition = "bills"
      # Delete from store
      record.then( (r) ->
        r.deleteRecord()
      )
      # Display list of record type
      @transitionTo(transition)
)

on line 4 the connection is being set and object are being fetched when i hit "/", but after i enter a route "/orders" object are not being fetched anymore, and on line 16 in the code above, i cant use the socket variable

Uncaught ReferenceError: socket is not defined

Is there a better way to manage this ?

解决方案

so the correct way to use a reusable socket is setting it inside the Store

App.Store = DS.Store.extend(
  revision: 12
  adapter: adapter
  socket: io.connect "http://localhost:4000/orders"
)

so then i can access to it inside any part of the code using

socket = @get 'store.socket'

这篇关于EmberJS全局websocket连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 16:22