我正在使用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
有没有更好的方法来管理它?
答案 0 :(得分:4)
所以使用可重用套接字的正确方法是在Store
中设置它App.Store = DS.Store.extend(
revision: 12
adapter: adapter
socket: io.connect "http://localhost:4000/orders"
)
所以我可以使用
在代码的任何部分内访问它socket = @get 'store.socket'
答案 1 :(得分:1)
套接字超出了范围,你可以在控制器上设置对它的引用并在以后检索它(原谅我的拙劣的coffeescript)
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)
)