Class: Browser::EventSource

Inherits:
Object show all
Includes:
Browser::Event::Target, Native
Defined in:
opal/browser/event_source.rb

Overview

An EventSource allows you to receive events from a server in real-time, similar to long-polling but not exactly.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Browser::Event::Target

#off, #on, #on!, #trigger, #trigger!

Constructor Details

#initialize(path) { ... } ⇒ EventSource

Create an Browser::EventSource on the given path.

Parameters:

  • path (String)

    the path to use as source

Yields:

  • if the block has no parameters it's instance_exec'd, otherwise it's called with self



24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'opal/browser/event_source.rb', line 24

def initialize(path, &block)
  if native?(path)
    super(path)
  else
    super(`new window.EventSource(path)`)
  end

  if block.arity == 0
    instance_exec(&block)
  else
    block.call(self)
  end if block
end

Instance Attribute Details

#state:connecting, ... (readonly)

Returns the state of the event source.

Returns:

  • (:connecting, :open, :closed)

    the state of the event source



44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'opal/browser/event_source.rb', line 44

def state
  %x{
    switch (#@native.readyState) {
      case window.EventSource.CONNECTING:
        return "connecting";

      case window.EventSource.OPEN:
        return "open";

      case window.EventSource.CLOSED:
        return "closed";
    }
  }
end

#urlString (readonly)

Returns the URL of the event source.

Returns:

  • (String)

    the URL of the event source



40
# File 'opal/browser/event_source.rb', line 40

alias_native :url

Class Method Details

.supported?Boolean

Returns:

  • (Boolean)


8
9
10
# File 'opal/browser/event_source.rb', line 8

def self.supported?
  Browser.supports? :EventSource
end

Instance Method Details

#alive?Boolean

Check if the event source is alive.

Returns:

  • (Boolean)


60
61
62
# File 'opal/browser/event_source.rb', line 60

def alive?
  state == :open
end

#closeObject

Close the event source.



65
66
67
# File 'opal/browser/event_source.rb', line 65

def close
  `#@native.close()`
end