1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00
rails--rails/lib/assets/javascripts/cable/subscriptions.coffee

81 lines
2.5 KiB
CoffeeScript
Raw Normal View History

2015-07-08 08:42:04 -04:00
# Collection class for creating (and internally managing) channel subscriptions. The only method intended to be triggered by the user
# us Cable.Subscriptions#create, and it should be called through the consumer like so:
#
# @App = {}
# App.cable = Cable.createConsumer "ws://example.com/accounts/1"
2015-07-08 08:42:04 -04:00
# App.appearance = App.cable.subscriptions.create "AppearanceChannel"
#
# For more details on how you'd configure an actual channel subscription, see Cable.Subscription.
class Cable.Subscriptions
constructor: (@consumer) ->
@subscriptions = []
@history = []
create: (channelName, mixin) ->
channel = channelName
params = if typeof channel is "object" then channel else {channel}
new Cable.Subscription this, params, mixin
2015-07-08 08:42:04 -04:00
# Private
add: (subscription) ->
@subscriptions.push(subscription)
@notify(subscription, "initialized")
@sendCommand(subscription, "subscribe")
reload: ->
for subscription in @subscriptions
@sendCommand(subscription, "subscribe")
rejectSubscription: (identifier) ->
subscriptions = @findAll(identifier)
for subscription in subscriptions
@removeSubscription(subscription)
@notify(subscription, "rejected")
remove: (subscription) ->
@removeSubscription(subscription)
unless @findAll(subscription.identifier).length
@sendCommand(subscription, "unsubscribe")
removeSubscription: (subscription) ->
@subscriptions = (s for s in @subscriptions when s isnt subscription)
findAll: (identifier) ->
s for s in @subscriptions when s.identifier is identifier
notifyAll: (callbackName, args...) ->
for subscription in @subscriptions
@notify(subscription, callbackName, args...)
notify: (subscription, callbackName, args...) ->
if typeof subscription is "string"
subscriptions = @findAll(subscription)
else
subscriptions = [subscription]
for subscription in subscriptions
subscription[callbackName]?(args...)
if callbackName in ["initialized", "connected", "disconnected", "rejected"]
{identifier} = subscription
@record(notification: {identifier, callbackName, args})
sendCommand: (subscription, command) ->
{identifier} = subscription
if identifier is Cable.PING_IDENTIFIER
@consumer.connection.isOpen()
else
@consumer.send({command, identifier})
record: (data) ->
data.time = new Date()
@history = @history.slice(-19)
@history.push(data)
toJSON: ->
history: @history
identifiers: (subscription.identifier for subscription in @subscriptions)