Skip to content

Control Refs #70

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Feb 22, 2022
Merged

Control Refs #70

merged 3 commits into from
Feb 22, 2022

Conversation

FeodorFitsner
Copy link
Contributor

To access control propeties you need to have a refence to that control, so currently you first declare that control and then add it to a layout, for example:

# controls that we need to access in the event handler
comments = Textbox(label="Comments", width="100%", multiline=True, auto_adjust_height=True, resizable=False)
is_public = Checkbox(label="Make public")

# event handler
def submit_click(e):
  # access control properties
  print(comments.value)
  print(is_public.value)

# layout
page.add(Stack(controls[
  comments,
  is_public,
  Button("Submit comment", on_click=submit_click)
]))

This PR introduces Ref[ControlType] that stores a refrence to a control object and allows keeping the entire layout in one place. The idea is similar to React Refs. With Refs the example above can be rewritten as:

# controls that we need to access in the event handler
comments = Ref[Textbox]()
is_public = Ref[Checkbox]()

# event handler
def submit_click(e):
  # access control properties
  # using <reference>.current
  print(comments.current.value)
  print(is_public.current.value)

# layout
page.add(Stack(controls[
  Textbox(ref=comments, label="Comments", width="100%", multiline=True, auto_adjust_height=True, resizable=False),
  Checkbox(ref=is_public, label="Make public"),
  Button("Submit comment", on_click=submit_click)
]))

You create a refrence object as Ref[<ControlType>]() then add ref=<reference> argument to a call to control init method, to bind control and reference together, and, finally, use <reference>.current property to access the control:

# declare reference to a Textbox
first_name = Ref[Textbox]()

# use the reference to access control properties
entered_text = first_name.current.value

# add control with a reference to a page
page.add(Textbox(ref=first_name, label="Enter some text"))

@FeodorFitsner FeodorFitsner merged commit ff9206d into main Feb 22, 2022
@FeodorFitsner FeodorFitsner deleted the control-refs branch February 22, 2022 19:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant