1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Assume subscribers have an identifier

This commit is contained in:
Javan Makhmali 2015-06-25 11:36:40 -04:00
parent 53d0b22aee
commit d9d7371c56
3 changed files with 26 additions and 22 deletions

View file

@ -13,8 +13,5 @@ class @Cable
params = if typeof channel is "object" then channel else {channel}
new Cable.Channel this, params, mixin
sendMessage: (identifier, data) ->
@sendCommand(identifier, "message", data)
sendCommand: (identifier, command, data) ->
@connection.send({identifier, command, data})
send: (data) ->
@connection.send(data)

View file

@ -2,7 +2,7 @@ class Cable.Channel
constructor: (@cable, params = {}, mixin) ->
@identifier = JSON.stringify(params)
extend(this, mixin)
@cable.subscribers.add(@identifier, this)
@cable.subscribers.add(this)
# Perform a channel action with the optional data passed as an attribute
perform: (action, data = {}) ->
@ -10,10 +10,10 @@ class Cable.Channel
@send(data)
send: (data) ->
@cable.sendMessage(@identifier, JSON.stringify(data))
@cable.send(command: "message", identifier: @identifier, data: JSON.stringify(data))
unsubscribe: ->
@cable.subscribers.remove(@identifier)
@cable.subscribers.remove(this)
extend = (object, properties) ->
if properties?

View file

@ -2,25 +2,32 @@ class Cable.SubscriberManager
constructor: (@cable) ->
@subscribers = {}
add: (identifier, subscriber) ->
add: (subscriber) ->
{identifier} = subscriber
@subscribers[identifier] = subscriber
if @cable.sendCommand(identifier, "subscribe")
@notify(identifier, "connected")
if @sendCommand("subscribe", identifier)
@notify(subscriber, "connected")
reload: ->
for identifier in Object.keys(@subscribers)
if @cable.sendCommand(identifier, "subscribe")
@notify(identifier, "connected")
for identifier, subscriber of @subscribers
if @sendCommand("subscribe", identifier)
@notify(subscriber, "connected")
remove: (identifier) ->
if subscriber = @subscribers[identifier]
@cable.sendCommand(identifier, "unsubscribe")
delete @subscribers[identifier]
remove: (subscriber) ->
{identifier} = subscriber
@sendCommand("unsubscribe", identifier)
delete @subscribers[identifier]
notifyAll: (event, args...) ->
for identifier in Object.keys(@subscribers)
@notify(identifier, event, args...)
for identifier, subscriber of @subscribers
@notify(subscriber, event, args...)
notify: (identifier, event, args...) ->
if subscriber = @subscribers[identifier]
notify: (subscriber, event, args...) ->
if typeof subscriber is "string"
subscriber = @subscribers[subscriber]
if subscriber
subscriber[event]?(args...)
sendCommand: (command, identifier) ->
@cable.send({command, identifier})