Merge pull request #1080 from Textualize/watcher_init

added init option
This commit is contained in:
Will McGugan
2022-11-01 09:35:10 +00:00
committed by GitHub
3 changed files with 14 additions and 3 deletions

View File

@@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/)
and this project adheres to [Semantic Versioning](http://semver.org/).
## [0.4.0] - Unreleased
### Added
- Added `init` param to reactive.watch
## [0.3.0] - 2022-10-31
### Fixed

View File

@@ -203,7 +203,7 @@ class DarkSwitch(Horizontal):
yield Static("Dark mode toggle", classes="label")
def on_mount(self) -> None:
watch(self.app, "dark", self.on_dark_change)
watch(self.app, "dark", self.on_dark_change, init=False)
def on_dark_change(self, dark: bool) -> None:
self.query_one(Checkbox).value = self.app.dark

View File

@@ -299,7 +299,10 @@ class var(Reactive[ReactiveType]):
def watch(
obj: Reactable, attribute_name: str, callback: Callable[[Any], object]
obj: Reactable,
attribute_name: str,
callback: Callable[[Any], object],
init: bool = True,
) -> None:
"""Watch a reactive variable on an object.
@@ -307,6 +310,7 @@ def watch(
obj (Reactable): The parent object.
attribute_name (str): The attribute to watch.
callback (Callable[[Any], object]): A callable to call when the attribute changes.
init (bool, optional): True to call watcher initialization. Defaults to True.
"""
watcher_name = f"__{attribute_name}_watchers"
current_value = getattr(obj, attribute_name, None)
@@ -314,4 +318,5 @@ def watch(
setattr(obj, watcher_name, WeakSet())
watchers = getattr(obj, watcher_name)
watchers.add(callback)
Reactive._check_watchers(obj, attribute_name, current_value)
if init:
Reactive._check_watchers(obj, attribute_name, current_value)