将HTML5 Websockets集成到Ember.js应用程序中的最佳方法是什么?
我过去使用过 Pusher.com,并使用了与此类似的设置:http://blog.pusher.com/backbone-js-now-realtime-with-pusher/
我正在寻找与Ember相当的东西.js
谢谢大家!
我已经使用套接字设置了一个应用程序。 我这样做的方法是我的主App文件有一个套接字对象,然后从 socket.io 接收消息并将它们放入数组中。 任何可能有兴趣侦听某些套接字消息的控制器都会绑定到阵列并获取传入的新消息。 例如,我的聊天控制器关心聊天消息,我的事件控制器关心根据触发的套接字事件显示或隐藏图像。
下面是我如何设置它的一些咖啡脚本代码。
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'
然后在我的聊天控制器中,我只监听收到的新消息
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')
在我的事件控制器中,我监听图像显示和图像隐藏
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')
您可以在 8 个月前的 GitHub 上查看以下内容,但目前没有WebSocketsAdapter
,尽管我很想看到一个。在大多数情况下,人们似乎正在为自己的场景制作临时WebSocketAdapter
。
我想一旦EmberJS发布1.0版本,那么你就会开始看到更多的第三方附加组件。由于 EmberJS,特别是 EmberJS 的 DS(DataStore)变化如此之快,除非您完全致力于保持它的最新状态,否则开始创建一个WebSocketAdapter
似乎有点为时过早,因为 EmberJS/DS 每天都在快速变化。