.on()
The.on() method creates a realtime subscription that triggers a callback whenever data changes. Unlike .once(), it continues listening indefinitely until explicitly unsubscribed.
Signature
Parameters
Function called whenever data changes at this node.Signature:
function(data, key, message, event)data- The updated datakey- The property key that changedmessage- Full message object with metadataevent- Event control object with.off()method
Subscription options
true- Shorthand for{change: true}, only fires on changes- Object with properties:
Return Value
Returns the same GUN chain reference for method chaining.Examples
Basic Subscription
Subscribe to Nested Properties
Change-Only Mode
Unsubscribe with .off()
Realtime Chat Example
Form Sync Example
Implementation Details
From the source code (on.js:4-52):.on() method:
- Sets up a persistent event listener
- Subscribes to the internal event system
- Receives all updates (initial data + changes)
- Supports filtering with the
changeoption - Returns immediately; data arrives asynchronously
Differences from .once()
| Feature | .on() | .once() |
|---|---|---|
| Triggers | Every update | One time only |
| Unsubscribe | Manual with .off() | Automatic |
| Use case | Realtime sync | Read current value |
| Performance | Stays in memory | Cleans up automatically |
Memory Management
Notes
.on()fires immediately with cached data, then on every change- Use
.off()to clean up subscriptions and prevent memory leaks - Callbacks receive data even if the value hasn’t changed (unless
change: true) - The callback is called with the gun chain as
thiscontext - Subscriptions survive reconnections and sync automatically
- For one-time reads, use
.once()instead