Skip to content

Instantly share code, notes, and snippets.

@1gor
Forked from jgaskins/toggle.rb
Created September 12, 2018 13:05
Show Gist options
  • Select an option

  • Save 1gor/1df83d2c4a55b7b04c45d2fe7120ae16 to your computer and use it in GitHub Desktop.

Select an option

Save 1gor/1df83d2c4a55b7b04c45d2fe7120ae16 to your computer and use it in GitHub Desktop.
Stateful Clearwater components using nested Clearwater apps
# Wrapper for a UI component that needs to maintain its own state
class Toggle
include Clearwater::BlackBoxNode
attr_reader :app, :component :state
def initialize(state=false)
@state = state
end
def mount element
@component = Component.new(@state)
@app = Clearwater::Application.new(component: component, element: element)
@app.render # No need to use `call` because we don't want to mount the app
end
def update previous
@app = previous.app
# uncomment the following line if you want to change the component's state with
# this wrapper's constructor params when updating:
# @component.state = @state
@app.render
end
# The actual UI component we're going to use
class Component
include Clearwater::Component
def initialize(state)
@state = state
end
def render
div(
onclick: method(:toggle!),
style: {
background_color: toggled? ? :green : red,
width: '1em',
height: '1em',
}
)
end
def toggle!
@state = !@state
end
def toggled?
!!@state
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment