Class: IfBinding

Inherits:
BaseBinding show all
Defined in:
lib/volt/page/bindings/if_binding.rb

Instance Attribute Summary

Attributes inherited from BaseBinding

#binding_name, #context, #target

Instance Method Summary collapse

Methods inherited from BaseBinding

#queue_update, #remove_anchors, #section, #value_from_getter

Constructor Details

#initialize(page, target, context, binding_name, branches) ⇒ IfBinding

Returns a new instance of IfBinding.



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/volt/page/bindings/if_binding.rb', line 4

def initialize(page, target, context, binding_name, branches)
  # puts "New If Binding: #{binding_name}, #{getter.inspect}"
  super(page, target, context, binding_name)

  getter, template_name = branches[0]

  @branches = []
  @listeners = []

  branches.each do |branch|
    getter, template_name = branch

    if getter.present?
      # Lookup the value
      value = value_from_getter(getter)

      if value.reactive?
        # Trigger change when value changes
        @listeners << value.on('changed') { update }
      end
    else
      # A nil value means this is an unconditional else branch, it
      # should always be true
      value = true
    end

    @branches << [value, template_name]
  end

  update
end

Instance Method Details

#removeObject



65
66
67
68
69
70
71
72
# File 'lib/volt/page/bindings/if_binding.rb', line 65

def remove
  # Remove all listeners on any reactive values
  @listeners.each(&:remove)

  @template.remove if @template

  super
end

#updateObject



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/volt/page/bindings/if_binding.rb', line 36

def update
  # Find the true branch
  true_template = nil
  @branches.each do |branch|
    value, template_name = branch

    # TODO: A bug in opal requires us to check == true
    if value.cur.true? == true
      # This branch is currently true
      true_template = template_name
      break
    end
  end

  # Change out the template only if the true branch has changed.
  if @last_true_template != true_template
    @last_true_template = true_template

    if @template
      @template.remove
      @template = nil
    end

    if true_template
      @template = TemplateRenderer.new(@page, @target, @context, binding_name, true_template)
    end
  end
end