Skip to main content

.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
Function called whenever data changes at this node.Signature: function(data, key, message, event)
  • data - The updated data
  • key - The property key that changed
  • message - Full message object with metadata
  • event - Event control object with .off() method
boolean | object
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):
The .on() method:
  1. Sets up a persistent event listener
  2. Subscribes to the internal event system
  3. Receives all updates (initial data + changes)
  4. Supports filtering with the change option
  5. Returns immediately; data arrives asynchronously

Differences from .once()

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 this context
  • Subscriptions survive reconnections and sync automatically
  • For one-time reads, use .once() instead