Class: Volt::Dependency
Overview
Dependencies are used to track the current computation so it can be re-run at a later point if this dependency changes.
You can also pass an on_dep and on_stop_dep proc’s to #initialize.
Instance Method Summary collapse
- #changed! ⇒ Object
- #depend ⇒ Object
-
#initialize(on_dep = nil, on_stop_dep = nil) ⇒ Dependency
constructor
Setup a new dependency.
-
#remove ⇒ Object
Called when a dependency is no longer needed.
Constructor Details
#initialize(on_dep = nil, on_stop_dep = nil) ⇒ Dependency
Setup a new dependency.
39 40 41 42 43 |
# File 'lib/volt/reactive/dependency.rb', line 39 def initialize(on_dep=nil, on_stop_dep=nil) @dependencies = Set.new @on_dep = on_dep @on_stop_dep = on_stop_dep end |
Instance Method Details
#changed! ⇒ Object
71 72 73 74 75 76 77 78 79 80 81 82 |
# File 'lib/volt/reactive/dependency.rb', line 71 def changed! deps = @dependencies # If no deps, dependency has been removed return unless deps @dependencies = Set.new deps.each(&:invalidate!) @on_stop_dep.call if @on_stop_dep end |
#depend ⇒ Object
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
# File 'lib/volt/reactive/dependency.rb', line 45 def depend # If there is no @dependencies, don't depend because it has been removed return unless @dependencies current = Computation.current if current added = @dependencies.add?(current) if added # The first time the dependency is depended on by this computation, we call on_dep @on_dep.call if @on_dep && @dependencies.size == 1 current.on_invalidate do # If @dependencies is nil, this Dependency has been removed if @dependencies # For set, .delete returns a boolean if it was deleted deleted = @dependencies.delete(current) # Call on stop dep if no more deps @on_stop_dep.call if @on_stop_dep && deleted && @dependencies.size == 0 end end end end end |
#remove ⇒ Object
Called when a dependency is no longer needed
85 86 87 88 |
# File 'lib/volt/reactive/dependency.rb', line 85 def remove changed! @dependencies = nil end |