gpt4 book ai didi

websocket - Ember.js 和 HTML5 WebSockets

转载 作者:行者123 更新时间:2023-12-02 00:12:49 25 4
gpt4 key购买 nike

将 HTML5 Websockets 集成到 Ember.js 应用程序中的最佳方式通常是什么?

我过去使用过 Pusher.com,并使用过与此类似的设置:http://blog.pusher.com/backbone-js-now-realtime-with-pusher/

我正在寻找与 Ember.js 等效的东西

谢谢大家!

最佳答案

我已经使用套接字设置了一个应用程序。我这样做的方式是我的主应用程序文件有一个套接字对象,然后从 socket.io 接收消息并将它们放入一个数组中。任何可能对监听某些套接字消息感兴趣的 Controller 都会绑定(bind)到数组并获取传入的新消息。例如,我的 chatController 关心聊天消息,而我的 eventController 关心基于触发的套接字事件显示或隐藏图像。

下面是我如何设置它的一些 coffeescript 代码。

window.App = Ember.Application.create

init: ->
@_super()
@setSocketIO()

##
# socket - socket.io object for communicating with the server
socket: null

##
# socketMessages - array used to store any socket.io messages emitted from the server
socketMessages: []

##
# setSocketIO - setup socket.io connection and message endpoints
setSocketIO: ->
@set 'socket', io.connect()

##
# if the socket errors out, then reconnect it
App.socket.on "error", (err) ->
App.socket.socket.reconnect()

##
# receive new messages
App.socket.on "event-message-receive", (data) =>
@createSocketMessage 'event-message-receive', data

##
# image url recieved
App.socket.on "event-image-set-receive", (data) =>
@createSocketMessage 'event-image-set-receive', data

##
# hide image recieved
App.socket.on "event-image-hide-receive", () =>
@createSocketMessage 'event-image-hide-receive'

然后在我的聊天 Controller 中我只监听收到的新消息

App.ChatController = Ember.ArrayController.extend

##
# chat messages
chatMessages: []

##
# socketMessageBinding - bind to the App.socketMessage message queue for receiving new messages from the server
socketMessagesBinding: 'App.socketMessages'

##
# socketMessageAdded - called whenever a socket.io message is sent from teh server
socketMessageAdded: (->
# get the newest item on the stack
socketMessage = @socketMessages[@socketMessages.length-1]

if socketMessage.type == 'event-message-receive'
@chatMessages.pushObject socketMessage.data
).observes('socketMessages.@each')

在我的事件 Controller 中,我监听图像显示和图像隐藏

App.EventController = Ember.ArrayController.extend

##
# property to show or hide an img on the page
showImage: false

##
# socketMessageBinding - bind to the App.socketMessage message queue for receiving new messages from the server
socketMessagesBinding: 'App.socketMessages'

##
# socketMessageAdded - called whenever a socket.io message is sent from teh server
socketMessageAdded: (->
# get the newest item on the stack
socketMessage = @socketMessages[@socketMessages.length-1]

if socketMessage.type == 'event-image-set-receive'
@set 'showImage', true
else if socketMessage.type == 'event-image-hide-receive'
@set 'showImage', false
).observes('socketMessages.@each')

关于websocket - Ember.js 和 HTML5 WebSockets,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14609477/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com