Class: React::Component::State

Inherits:
Object
  • Object
show all
Includes:
Native::Wrapper
Defined in:
lib/react/component/state.rb

Instance Method Summary collapse

Constructor Details

#initialize(native) ⇒ State

Returns a new instance of State.



6
7
8
# File 'lib/react/component/state.rb', line 6

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



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/react/component/state.rb', line 10

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

#set_state(updater, &block) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
# File 'lib/react/component/state.rb', line 27

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



39
40
41
# File 'lib/react/component/state.rb', line 39

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

#to_nObject



43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/react/component/state.rb', line 43

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