Skip to content

world.subscribe(listener) ​

Chiama il tuo listener con il mondo subito e di nuovo dopo ogni cambiamento. Restituisce una funzione che ferma le chiamate.

subscribe(listener: (node: GuiNode) => void): () => void
js
const stop = world.subscribe((node) => draw(node));

Parametri ​

ParametroChe cos'è
listenerLa callback che riceve il mondo più recente (chiamato node nelle callback) subito e poi dopo ogni cambiamento.

Valore restituito ​

Una funzione stop() che mette fine alle chiamate del tuo listener e non fa danni se chiamata due volte.

Uso ​

Disegnare il mondo a ogni cambiamento ​

Ogni vista funziona così. La tua pagina non modifica mai il mondo e lo segue disegnando tutto da node a ogni chiamata.

js
const world = await connectToHost();

world.subscribe((node) => {
  title.textContent = node.name;
  status.textContent = node.now?.text ?? '';
  sendButton.disabled = !node.canSend;
});

Smettere di seguire il mondo ​

Conserva la funzione restituita da subscribe e chiamala quando una parte della tua pagina viene rimossa. In questo esempio la vista si ferma dopo tre chiamate:

jsx
import { useEffect, useState } from 'react';
import { useWorld } from './useWorld.js';

// A fake world whose number of visitors changes every second.
const library = {
	name: 'Library',
	data: { visitors: (time) => 10 + (Math.floor(time / 1000) % 5) },
};

export default function App() {
	// While building: the fake world. In the webapp: useWorld()
	// useWorld subscribes for you. Here we also call `subscribe` ourselves to see each call.
	const { world, error } = useWorld({ fake: { world: library } });
	const [lines, setLines] = useState([]);
	const [isStopped, setIsStopped] = useState(false);
	const isConnected = world !== null;

	useEffect(() => {
		if (!isConnected) return undefined;
		// `subscribe` calls the function at once with the world, then after every change.
		// It returns a function that stops it. This example stops after three calls.
		let calls = 0;
		const stop = world.subscribe((node) => {
			calls += 1;
			const line = `Call ${calls}: ${node.data.visitors} visitors`;
			setLines((before) => [...before, line]);
			if (calls === 3) {
				stop();
				setIsStopped(true);
			}
		});
		return stop;
		// Subscribe once, when the world arrives.
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [isConnected]);

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;
	return (
		<>
			<h2>{world.name}</h2>
			<ol>
				{lines.map((line) => <li key={line}>{line}</li>)}
			</ol>
			<p>{isStopped ? 'Stopped after 3 calls.' : ''}</p>
		</>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// A fake world whose number of visitors changes every second.
const library = {
	name: 'Library',
	data: { visitors: (time) => 10 + (Math.floor(time / 1000) % 5) },
};

// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: library } });

const title = document.createElement('h2');
const list = document.createElement('ol');
const note = document.createElement('p');
document.body.append(title, list, note);

// `subscribe` calls the function at once with the world, then after every change.
// It returns a function that stops it. This example stops after three calls.
let calls = 0;
const stop = world.subscribe((node) => {
	calls += 1;
	title.textContent = node.name;
	const line = document.createElement('li');
	line.textContent = `Call ${calls}: ${node.data.visitors} visitors`;
	list.append(line);
	if (calls === 3) {
		stop();
		note.textContent = 'Stopped after 3 calls.';
	}
});
Live, on a fake world
Open

La prima chiamata arriva già prima che subscribe ritorni. Ogni cambiamento porta una nuova chiamata (qui un nuovo numero di visitatori ogni secondo).

In React ​

L'hook useWorld chiama subscribe al posto tuo e fa il re-render del tuo componente a ogni cambiamento. Chiama subscribe da te solo per un lavoro fuori dal rendering. Fallo in un useEffect che restituisce la funzione stop come fa la scheda React qui sopra.

Avvertenze ​

  • La prima chiamata avviene dentro subscribe. Crea gli elementi che il tuo listener riempie prima di chiamare subscribe.
  • Ogni chiamata riceve un nuovo mondo congelato. Scriverci dentro lancia un TypeError. Tieni quello che ti serve in variabili tue.
  • Molte cose contano come un cambiamento: un nuovo messaggio, un nuovo valore in data, un nuovo now o un cambiamento in webapp come il tema o la tastiera. Disegna ogni volta tutto il mondo invece di indovinare che cosa è cambiato.
  • Tieni veloce il tuo listener. Un mondo che mostra una fotocamera cambia molte volte al secondo. Quando cambia solo data il kit chiama il tuo listener al massimo circa una volta per frame dello schermo. Anche a questa frequenza un listener lento rallenta la tua pagina. Per un solo valore che cambia in fretta usa onData.
  • Un listener che lancia un'eccezione può impedire agli altri listener di ricevere quel cambiamento. Cattura gli errori dentro il tuo listener.
  • Puoi chiamare subscribe più di una volta (per esempio una per ogni parte della tua pagina) e ogni chiamata ha il suo stop.

Risoluzione dei problemi ​

subscribe non fallisce mai e non ha codici di errore.

ProblemaCausaChe cosa fare
La pagina mostra il mondo com'era all'avvio.La vista ha disegnato world una volta dopo connectToHost. Quell'oggetto è il primo mondo e non cambia mai.Disegna da node dentro subscribe.
Un handler di clic vede valori vecchi.L'handler ha conservato un mondo di una chiamata precedente.Leggi world.get() dentro l'handler.
In React il listener viene eseguito due volte per cambiamento.Chiami subscribe in un effect che viene rieseguito a ogni render.Chiama subscribe una volta come nella scheda React qui sopra oppure usa il mondo restituito da useWorld.

Vedi anche ​

Il GUI kit di UNaIVERSE, rilasciato con licenza Apache 2.0. Copyright 2024-2026 UNaIVERSE S.r.l.