Sha256: f6f07c196b7bb6ce2ef9f1d443e31de3e3aed4ce7d6b62f2d3031855f517392f

Contents?: true

Size: 1.79 KB

Versions: 9

Compression:

Stored size: 1.79 KB

Contents

class ReactiveBlock
  include ReactiveTags

  def reactive?
    true
  end

  def initialize(source, check_block, run_block)
    @source = ReactiveValue.new(source)
    @check_block = check_block
    @run_block = run_block
  end

  def cur
    val = @run_block.call(@source)

    return val
  end

  def setup_listeners
    @cell_trackers = []
    @setup = false
    @added_tracker = @source.on('added') do |_, index|
      change_cell_count(@source.size.cur)
    end

    @removed_tracker = @source.on('removed') do |_, index|
      change_cell_count(@source.size.cur)
    end

    @setup = true

    # Initial cell tracking
    change_cell_count(@source.size.cur)
  end

  # We need to make sure we're listening on the result from each cell,
  # that way we can trigger when the value changes.
  def change_cell_count(size)
    current_size = @cell_trackers.size

    if current_size < size
      # Add trackers

      current_size.upto(size-1) do |index|
        # Get the reactive value for the index
        val = @source[index]

        result = @check_block.call(val)

        @cell_trackers << result.on('changed') do
          puts "RESULT CHANGED: #{index} - #{self.object_id}"
          trigger!('changed')
        end
      end
    elsif current_size > size
      (current_size-1).downto(size) do |index|
        @cell_trackers[index].remove
        @cell_trackers.delete_at(index)
      end
    end
  end


  def teardown_listeners
    @added_tracker.remove
    @added_tracker = nil

    @removed_tracker.remove
    @removed_tracker = nil

    change_cell_count(0)

    @cell_trackers = nil
  end

  def event_added(event, scope_provider, first, first_for_event)
    setup_listeners if first
  end

  def event_removed(event, last, last_for_event)
    teardown_listeners if last
  end

  def inspect
    "@#{cur}"
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
volt-0.7.23 lib/volt/reactive/reactive_block.rb
volt-0.7.22 lib/volt/reactive/reactive_block.rb
volt-0.7.21 lib/volt/reactive/reactive_block.rb
volt-0.7.20 lib/volt/reactive/reactive_block.rb
volt-0.7.19 lib/volt/reactive/reactive_block.rb
volt-0.7.18 lib/volt/reactive/reactive_block.rb
volt-0.7.17 lib/volt/reactive/reactive_block.rb
volt-0.7.16 lib/volt/reactive/reactive_block.rb
volt-0.7.15 lib/volt/reactive/reactive_block.rb