counter.py 1.1 KB

123456789101112131415161718192021222324252627282930313233
  1. from typing import Callable, Optional
  2. from addict import Dict
  3. from nicegui.elements.custom_view import CustomView
  4. from nicegui.elements.element import Element
  5. from nicegui.routes import add_dependencies
  6. add_dependencies(__file__) # automatically serve the .js file with the same name
  7. class CounterView(CustomView):
  8. def __init__(self, title: str, on_change: Optional[Callable]) -> None:
  9. super().__init__('counter', title=title, value=0) # pass props to the Vue component
  10. self.on_change = on_change
  11. self.allowed_events = ['onChange']
  12. self.initialize(temp=False, onChange=self.handle_change)
  13. def handle_change(self, msg: Dict) -> None:
  14. if self.on_change is not None:
  15. self.on_change(msg.value)
  16. return False # avoid JustPy's page update
  17. class Counter(Element):
  18. def __init__(self, title: str, *, on_change: Optional[Callable] = None) -> None:
  19. super().__init__(CounterView(title, on_change))
  20. def reset(self) -> None:
  21. self.view.options.value = 0
  22. self.update() # update the view after changing the counter value