Skip to content

Commit

Permalink
try to automatically add new elements into the parent container of th…
Browse files Browse the repository at this point in the history
…e event sender
  • Loading branch information
falkoschindler committed Sep 23, 2022
1 parent 4ee8035 commit e4af107
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 6 deletions.
3 changes: 2 additions & 1 deletion nicegui/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,8 @@ def handle_event(handler: Optional[Callable], arguments: EventArguments) -> Opti
if handler is None:
return False
no_arguments = not signature(handler).parameters
result = handler() if no_arguments else handler(arguments)
with globals.within_view(arguments.sender.parent_view):
result = handler() if no_arguments else handler(arguments)
if is_coroutine(handler):
if globals.loop and globals.loop.is_running():
create_task(result, name=str(handler))
Expand Down
14 changes: 13 additions & 1 deletion nicegui/globals.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,16 @@

import asyncio
import logging
from typing import Awaitable, Callable, Dict, List, Optional, Union
from contextlib import contextmanager
from typing import Awaitable, Callable, Dict, Generator, List, Optional, Union

import justpy as jp
from starlette.applications import Starlette
from uvicorn import Server

from .config import Config
from .page_builder import PageBuilder
from .task_logger import create_task

app: Starlette
config: Optional[Config] = None
Expand All @@ -30,3 +32,13 @@ def find_route(function: Callable) -> str:
if not routes:
raise ValueError(f'Invalid page function {function}')
return routes[0]


@contextmanager
def within_view(view: jp.HTMLBaseComponent) -> Generator[None, None, None]:
child_count = len(view)
view_stack.append(view)
yield
view_stack.pop()
if len(view) != child_count:
create_task(view.update())
10 changes: 6 additions & 4 deletions nicegui/timer.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from . import globals
from .binding import BindableProperty
from .helpers import is_coroutine
from .page import find_parent_view
from .task_logger import create_task

NamedCoroutine = namedtuple('NamedCoroutine', ['name', 'coro'])
Expand All @@ -32,13 +33,14 @@ def __init__(self, interval: float, callback: Callable, *, active: bool = True,

self.active = active
self.interval = interval
self.parent_view = find_parent_view()

async def do_callback():
try:
if is_coroutine(callback):
return await callback()
else:
return callback()
with globals.within_view(self.parent_view):
result = callback()
if is_coroutine(callback):
await result
except Exception:
traceback.print_exc()

Expand Down

0 comments on commit e4af107

Please sign in to comment.