Replies: 2 comments 8 replies
-
Wanted to add an afterthought: My best guess is that this needs a "Channels" solution, so a central exchange for data that can be made available via dependency injection. The websocket server callback then just pushes data to that exchange and forwards incoming messages to the connection. Does that make sense? |
Beta Was this translation helpful? Give feedback.
-
Hi @aranvir, One possibility that just came into my mind is to use the rather new import asyncio
import time
from nicegui import ElementFilter, app, ui
ui.label().mark('clock')
def update_clock():
for element in ElementFilter(kind=ui.label, marker='clock'):
element.text = time.strftime('%H:%M:%S')
async def run_clock():
while True:
update_clock()
await asyncio.sleep(1)
ui.run() |
Beta Was this translation helpful? Give feedback.
-
Question
Hi, I spent a couple of ours playing around with nicegui and I'm really impressed by the possibilities! However, I struggle a bit with translating the simple examples into the context of a multi-page application.
Elements defined in a function decorated with
ui.page
are private to the client. If I want to run something like the websocket example within a page it does not work correct.The websocket server and the
handle_connect
hook have to be defined globally, but the elements that they are supposed to update are limited to the function scope. I also tried to put all of it in a class, and that works somewhat, but is a buggy solution withClient has been deleted but is still being used.
messages popping up whenever I leave the page but continue to send messages via websocket.So yea, hence the title question is: How can global callbacks/background processes access local ui elements?
I added my approach below which also includes an example. This works fine as long as the page is open. Once it's closed it wont work anymore, e.g.:
/web-sockets
/
web-sockets
will allow to receive messages again but the connections counter will not be updatedBeta Was this translation helpful? Give feedback.
All reactions