Class: Preact::State

Inherits:
Object show all
Includes:
Native::Wrapper
Defined in:
lib/preact/state.rb

Instance Method Summary collapse

Constructor Details

#initialize(native) ⇒ State

Returns a new instance of State.



5
6
7
# File 'lib/preact/state.rb', line 5

def initialize(native)
  @native = native
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(key, *args, &block) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/preact/state.rb', line 36

def method_missing(key, *args, &block)
  if `args.length > 0`
    new_state = `{}`
    new_state.JS[(`key.endsWith('=')` ? key.chop : key)] = args[0]
    if block_given?
      @native.JS.setState(new_state, `function() { block.$call(); }`)
    else
      @native.JS.setState(new_state, `null`)
    end
  else
    %x{
      if (typeof #@native.state[key] === 'undefined') { return nil; }
      return #@native.state[key];
    }
  end
end

Instance Method Details

#==(other_state) ⇒ Object



9
10
11
12
13
14
# File 'lib/preact/state.rb', line 9

def ==(other_state)
  %x{
    if (Opal.Preact.state_is_not_equal(#@native.state, #{other_state.to_raw_n})) { return false; }
    return true;
  }
end

#[](key) ⇒ Object



16
17
18
19
20
21
# File 'lib/preact/state.rb', line 16

def [](key)
  %x{
    if (typeof #@native.state[key] === 'undefined') { return nil; }
    return #@native.state[key];
  }
end

#[]=(key) ⇒ Object



23
24
25
26
27
# File 'lib/preact/state.rb', line 23

def []=(key)
  new_state = `{}`
  new_state.JS[(`key.endsWith('=')` ? key.chop : key)] = args[0]
  @native.JS.setState(new_state, `null`)
end

#key?(k) ⇒ Boolean

Returns:

  • (Boolean)


29
30
31
32
33
34
# File 'lib/preact/state.rb', line 29

def key?(k)
  %x{
    if (typeof #@native.state[k] !== 'undefined') { return true; }
    return false;
  }
end

#set_state(updater, &block) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
# File 'lib/preact/state.rb', line 53

def set_state(updater, &block)
  new_state = `{}`
  updater.each do |key, value|
    new_state.JS[key] = value
  end
  if block_given?
    @native.JS.setState(new_state, `function() { block.$call(); }`)
  else
    @native.JS.setState(new_state, `null`)
  end
end

#sizeObject



65
66
67
# File 'lib/preact/state.rb', line 65

def size
  `Object.keys(#@native.state).length`;
end

#to_nObject



69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/preact/state.rb', line 69

def to_n
  %x{
    var new_native = {};
    for (var key in #@native.state) {
      if (typeof #@native.state[key].$to_n !== "undefined") {
        new_native[key] = #@native.state[key].$to_n();
      } else {
        new_native[key] = #@native.state[key];
      }
    }
    return new_native;
  }
end

#to_raw_nObject



83
84
85
# File 'lib/preact/state.rb', line 83

def to_raw_n
  `#@native.state`
end