Sha256: 9633f3de201dd6467e92551af1ae9266c35d7c32db257f90bb54449101f17f83

Contents?: true

Size: 1.74 KB

Versions: 9

Compression:

Stored size: 1.74 KB

Contents

require 'volt/page/bindings/base_binding'

class IfBinding < BaseBinding
  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

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

      current_value = value.cur

      # TODO: A bug in opal requires us to check == true
      if current_value.true? == true && !current_value.is_a?(Exception)
        # 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

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

    @template.remove if @template

    super
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
volt-0.7.10 lib/volt/page/bindings/if_binding.rb
volt-0.7.9 lib/volt/page/bindings/if_binding.rb
volt-0.7.8 lib/volt/page/bindings/if_binding.rb
volt-0.7.7 lib/volt/page/bindings/if_binding.rb
volt-0.7.6 lib/volt/page/bindings/if_binding.rb
volt-0.7.5 lib/volt/page/bindings/if_binding.rb
volt-0.7.4 lib/volt/page/bindings/if_binding.rb
volt-0.7.3 lib/volt/page/bindings/if_binding.rb
volt-0.7.2 lib/volt/page/bindings/if_binding.rb