Skip to content

Commit

Permalink
example: custom binding
Browse files Browse the repository at this point in the history
  • Loading branch information
rodja committed Sep 8, 2023
1 parent 97261a6 commit d239645
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
41 changes: 41 additions & 0 deletions examples/custom_binding/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
#!/usr/bin/env python3

import random

from nicegui import ui
from nicegui.binding import BindableProperty, bind_from


class colorful_label(ui.label):
"""A label with a bindable background color."""

# this class variable defines what happens when the background property changes
background = BindableProperty(on_change=lambda sender, bg: sender.on_background_change(bg))

def __init__(self, text: str):
super().__init__(text)
self.background = None # initialize the background property

def on_background_change(self, bg: str) -> None:
"""Update the classes of the label when the background property changes."""
self._classes = [c for c in self._classes if not c.startswith('bg-')]
self._classes.append(bg)
self.update()


def shuffle():
for key in data:
data[key] = random.choice([True, False])


ui.button('shuffle', on_click=shuffle)
data = {}
for k in 'abcde':
data[k] = random.choice([True, False])
label = colorful_label(k.upper()).classes('w-48 text-center')
# binding from the data to the label
# there is also a bind_to method which would propagate changes from the label to the data
# and a bind method which would propagate changes both ways
bind_from(label, 'background', data, k, backward=lambda x: 'bg-green' if x else 'bg-red')

ui.run()
1 change: 1 addition & 0 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,7 @@ async def index_page(client: Client) -> None:
'[zauberzeug/nicegui](https://hub.docker.com/r/zauberzeug/nicegui) docker image')
example_link('Download Text as File', 'providing in-memory data like strings as file download')
example_link('Generate PDF', 'create SVG preview and PDF download from input form elements')
example_link('Custom Binding', 'create a custom binding for a label with a bindable background color')

with ui.row().classes('dark-box min-h-screen mt-16'):
link_target('why')
Expand Down

0 comments on commit d239645

Please sign in to comment.