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
Rafael Mendonça França eb8c713c98 .js.coffee -> .coffee
It was initially required, but support for the shorthand has been
 supported since sprockets 2.1. Eventually 4.x will only support the
 shorthand version. Just want to get new people using the prefer stuff
 ASAP.
2015-09-02 02:57:38 -03:00

71 lines
2.3 KiB
CoffeeScript

# 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"
# 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
# Private
add: (subscription) ->
@subscriptions.push(subscription)
@notify(subscription, "initialized")
if @sendCommand(subscription, "subscribe")
@notify(subscription, "connected")
reload: ->
for subscription in @subscriptions
if @sendCommand(subscription, "subscribe")
@notify(subscription, "connected")
remove: (subscription) ->
@subscriptions = (s for s in @subscriptions when s isnt subscription)
unless @findAll(subscription.identifier).length
@sendCommand(subscription, "unsubscribe")
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"]
{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)