world.onData(name, listener)
Chiama il tuo listener con ogni nuovo valore di data[name] e restituisce una funzione che ferma le chiamate.
onData(name: string, listener: (value: unknown) => void): () => void
js
const stop = world.onData('camera', (frame) => { picture.src = frame; });Parametri
| Parametro | Che cos'è |
|---|---|
name | Un nome di data come 'camera'. |
listener | La callback che riceve ogni nuovo valore nella stessa forma che ha in data. |
Valore restituito
Una funzione stop() che mette fine alle chiamate del tuo listener.
Uso
Seguire un valore
Poiché onData non passa il valore attuale, la vista lo legge prima dal mondo. In questo esempio il mondo finto invia una nuova temperatura ogni mezzo secondo e la vista si ferma dopo cinque valori:
jsx
import { useEffect, useState } from 'react';
import { useWorld } from './useWorld.js';
// A fake weather station that gives a new temperature every half second.
const station = {
name: 'Weather station',
data: { temperature: { every: 500, value: (time) => 20 + (Math.floor(time / 500) % 4) } },
};
export default function App() {
// While building: the fake world. In the webapp: useWorld()
const { world, error } = useWorld({ fake: { world: station } });
const [first, setFirst] = useState(null);
const [values, setValues] = useState([]);
const [isStopped, setIsStopped] = useState(false);
const isConnected = world !== null;
useEffect(() => {
if (!isConnected) return undefined;
// `onData` does not give the value the world has now. Read it from the world.
setFirst(world.data.temperature);
// Then it calls the function with each new value of one name of `data`.
// It returns a function that stops it. This example stops after five values.
let count = 0;
const stop = world.onData('temperature', (value) => {
count += 1;
setValues((before) => [...before, value]);
if (count === 5) {
stop();
setIsStopped(true);
}
});
return stop;
// Follow the value 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 (
<>
<p>At the start: {first} °C</p>
<ul>
{values.map((value, index) => <li key={index}>New value: {value} °C</li>)}
</ul>
<p>{isStopped ? 'Stopped after 5 values.' : ''}</p>
</>
);
}js
import { connectToHost } from '@unaiverse/gui-kit';
// A fake weather station that gives a new temperature every half second.
const station = {
name: 'Weather station',
data: { temperature: { every: 500, value: (time) => 20 + (Math.floor(time / 500) % 4) } },
};
// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: station } });
const first = document.createElement('p');
const list = document.createElement('ul');
const note = document.createElement('p');
document.body.append(first, list, note);
// `onData` does not give the value the world has now. Read it from the world.
first.textContent = `At the start: ${world.get().data.temperature} °C`;
// Then it calls the function with each new value of one name of `data`.
// It returns a function that stops it. This example stops after five values.
let count = 0;
const stop = world.onData('temperature', (value) => {
count += 1;
const item = document.createElement('li');
item.textContent = `New value: ${value} °C`;
list.append(item);
if (count === 5) {
stop();
note.textContent = 'Stopped after 5 values.';
}
});Mostrare una fotocamera senza ridisegnare tutta la vista
Un mondo che mostra una fotocamera cambia molte volte al secondo. Il listener scrive ogni fotogramma in un unico <img> e lascia intatto il resto della tua vista:
js
const picture = document.createElement('img');
picture.src = world.get().data.camera ?? '';
world.onData('camera', (frame) => {
picture.src = frame;
});In React
Appena connectToHost si è risolta, chiama onData in un useEffect che restituisce la funzione stop (è proprio quello che fa la scheda React qui sopra).
Avvertenze
- Solo valori nuovi. Il tuo listener non riceve mai il valore che il mondo ha quando chiami
onData. Leggi quel valore daworld.get().data[name]. - Dentro la webapp il listener viene eseguito solo quando il valore cambia e al massimo circa una volta per frame dello schermo. Un mondo finto lo chiama per ogni valore che dà anche quando il valore è uguale al precedente. Non contare le chiamate per misurare il tempo.
- Anche i tuoi listener di
subscribevengono eseguiti quando un valore cambia. UsaonDataper un piccolo compito su un solo valore e lascia che il resto della vista si aggiorni come al solito. - Per un nome che non compare mai in
datail listener non viene mai chiamato. Controlla il nome inObject.keys(world.get().data).
Risoluzione dei problemi
onData non fallisce mai e non ha codici di errore.
| Problema | Causa | Che cosa fare |
|---|---|---|
| All'inizio l'immagine è vuota. | onData passa solo i valori nuovi. | Riempila prima da world.get().data come nell'esempio della fotocamera. |
| Il listener non viene mai chiamato. | Il nome non è in data oppure il valore non cambia mai. | Guarda Object.keys(world.get().data) o chiedi i nomi al proprietario del mondo. |
Vedi anche
world.dataHistory(name): i valori recenti di un nome.world.subscribe(listener): tutto il mondo a ogni cambiamento.- La ricetta Segui i dati veloci senza rallentare e Prestazioni.