aboutsummaryrefslogtreecommitdiffstats
path: root/actioncable/app/assets/javascripts/action_cable/subscriptions.coffee
blob: d3ce67135d4f42e4f175542d86a46dbfb614fdaa (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# Collection class for creating (and internally managing) channel subscriptions. The only method intended to be triggered by the user
# us ActionCable.Subscriptions#create, and it should be called through the consumer like so:
#
#   @App = {}
#   App.cable = ActionCable.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 ActionCable.Subscription.
class ActionCable.Subscriptions
  constructor: (@consumer) ->
    @subscriptions = []

  create: (channelName, mixin) ->
    channel = channelName
    params = if typeof channel is "object" then channel else {channel}
    subscription = new ActionCable.Subscription @consumer, params, mixin
    @add(subscription)

    subscription

  # Private

  add: (subscription) ->
    @subscriptions.push(subscription)
    @consumer.ensureActiveConnection()
    @notify(subscription, "initialized")
    @sendCommand(subscription, "subscribe")

  remove: (subscription) ->
    @forget(subscription)

    unless @findAll(subscription.identifier).length
      @sendCommand(subscription, "unsubscribe")

  reject: (identifier) ->
    for subscription in @findAll(identifier)
      @forget(subscription)
      @notify(subscription, "rejected")

  forget: (subscription) ->
    @subscriptions = (s for s in @subscriptions when s isnt subscription)

  findAll: (identifier) ->
    s for s in @subscriptions when s.identifier is identifier

  reload: ->
    for subscription in @subscriptions
      @sendCommand(subscription, "subscribe")

  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...)

  sendCommand: (subscription, command) ->
    {identifier} = subscription
    @consumer.send({command, identifier})