0

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

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

在第 4 行,当我点击“/”时,正在设置连接并获取对象,但是在我输入路线后,“/orders”对象不再被获取,在上面代码的第 16 行,我无法使用套接字变量

Uncaught ReferenceError: socket is not defined

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

4

2 回答 2

4

所以使用可重用套接字的正确方法是将其设置在 Store 中

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

所以我可以在代码的任何部分使用

socket = @get 'store.socket'
于 2013-11-11T03:14:51.580 回答
1

一旦你点击了 markAsDone 方法,套接字就超出了范围,你可以在控制器上设置对它的引用并稍后检索它(请原谅我拙劣的咖啡脚本)

  App.ApplicationRoute = Ember.Route.extend(
  setupController: (controller, data) ->
    store  = @get 'store'
    socket = io.connect "http://localhost:4000/orders" ## Line 4
    ///////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////// 
    controller.set 'socket', socket
    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) ->
      ///////////////////////////////////////////////////////////////////////////
      ///////////////////////////////////////////////////////////////////////////
      socket = @get 'controller.socket'
      # 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)
)
于 2013-11-10T23:24:32.917 回答