Class: Browser::EventSource

Inherits:
Object show all
Includes:
Browser::Event::Target, Native::Wrapper
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!, #one, #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



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

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



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

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



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

alias_native :url

Class Method Details

.supported?Boolean

Returns:

  • (Boolean)


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

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

Instance Method Details

#alive?Boolean

Check if the event source is alive.

Returns:

  • (Boolean)


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

def alive?
  state == :open
end

#closeObject

Close the event source.



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

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