Sha256: b1510ba752bf9d091cf4e5baa3c4c9b650856609a0e7d730cb1f77483afc70f3

Contents?: true

Size: 1.57 KB

Versions: 1

Compression:

Stored size: 1.57 KB

Contents

#= require "moz_websocket"
#= require "vendor/jquery.json-2.2"
#= require "vendor/swfobject"
#= require "vendor/web_socket"
//= provide "../swf"

window.WEB_SOCKET_SWF_LOCATION = "<%= asset_path 'WebSocketMain.swf' %>"

class @AlondraClient
  constructor: (host, port, channels, token = null, retry = 5000) ->
    @channels = channels
    @token    = token
    @retry    = retry
    @url = "ws://#{host}:#{port}"

    @url += "?token=#{@token}" if @token

    this.connect()

  subscribe: (channel) ->
    subscription =
      command: 'subscribe'
      channel: channel

    @socket.send $.toJSON(subscription)

  connect: ->
    @socket   = new WebSocket(@url)

    @socket.onopen = () =>
      if @reconnectInterval
        clearInterval(@reconnectInterval)
        @reconnectInterval = null

      if @channels instanceof Array
        this.subscribe(channel) for channel in @channels
      else
        this.subscribe(@channels)

    @socket.onclose = () =>
      this.reconnect()


    @socket.onmessage = (message) =>
      msg = $.parseJSON(message.data)
      if msg.event
        this.process(msg)
      else
        this.execute(msg)


    @socket.onerror = (error) =>
      this.reconnect()

  process: (serverEvent) ->
    eventName    = serverEvent.event
    resourceType = serverEvent.resource_type
    resource     = serverEvent.resource

    $(this).trigger("#{eventName}.#{resourceType}", resource)

  execute: (message) ->
    eval(message.message)

  reconnect: ->
    return if !@retry || @reconnectInterval

    @reconnectInterval = setInterval =>
      this.connect()
    ,@retry

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
alondra-0.0.3 app/assets/javascripts/alondra-client.js.coffee.erb