New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details
Socket
Book a DemoSign in
Socket

lazy-watch

Package Overview
Dependencies
Maintainers
1
Versions
34
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

lazy-watch

Deep watch objects (using Proxy) and emit diff asynchronously.

latest
Source
npmnpm
Version
2.5.2
Version published
Maintainers
1
Created
Source

LazyWatch

npm version License: ISC

Deep watch JavaScript objects using Proxy and emit diffs asynchronously. LazyWatch efficiently tracks changes to objects (including nested properties and arrays) and batches multiple changes into a single update event.

Features

  • 🔄 Deep object watching with Proxy
  • ⏱️ Asynchronous batched updates
  • 🔍 Detailed change tracking with diffs
  • 🧩 Support for nested objects and arrays
  • ⏸️ Pause and resume event emissions
  • 🤫 Silent mutations without triggering events
  • 📦 Efficient patching mechanism
  • 🌐 Works in browsers and Node.js

Installation

npm install lazy-watch

Basic Usage

// Create a watched object
const UI = new LazyWatch({});

// Listen for changes
LazyWatch.on(UI, diff => console.log({ diff }));

// Make changes
UI.hello = 'world';
// After the next tick, logs: { diff: { hello: 'world' } }

With Throttling

// Create a watched object with 50ms throttle
const UI = new LazyWatch({}, { throttle: 50 });

LazyWatch.on(UI, diff => console.log({ diff }));

// Multiple rapid changes will be batched
UI.count = 1;
UI.count = 2;
UI.count = 3;
// After 50ms, logs once: { diff: { count: 3 } }

API Reference

Creating Watched Objects

const watchedObject = new LazyWatch(originalObject, options);

Creates a proxy around the original object that tracks all changes.

Parameters:

  • originalObject - The object or array to watch
  • options (optional) - Configuration options
    • throttle - Minimum time in milliseconds between emits (default: 0). When set, the first change emits immediately, but subsequent changes within the throttle window are batched together.

Listening for Changes

LazyWatch.on(watchedObject, callback);

Registers a callback function that will be called with a diff object whenever changes are made to the watched object.

Nested Proxy Listeners

Listeners can be registered on nested objects or arrays within a watched object. When you register a listener on a nested proxy, it receives path-relative diffs - only the changes relevant to that subtree, rather than the full root diff.

Example:

const data = new LazyWatch({
  root: {
    count: 1
  }
}, { throttle: 15 });

// Listener on the root proxy receives full diffs
LazyWatch.on(data, change => {
  console.log('Root:', JSON.stringify(change));
  // Logs: Root: {"root":{"count":2}}
});

// Listener on nested proxy receives path-relative diffs
LazyWatch.on(data.root, change => {
  console.log('Nested:', JSON.stringify(change));
  // Logs: Nested: {"count":2}
});

data.root.count++;

This feature is particularly useful when:

  • You want to listen to changes in specific parts of a large state object
  • Different components manage different sections of your application state
  • You need granular control over which changes trigger specific handlers

Multi-level nesting example:

const app = new LazyWatch({
  user: { name: 'Alice', preferences: { theme: 'dark' } },
  settings: { lang: 'en' }
});

// Only notified when user changes
LazyWatch.on(app.user, changes => {
  console.log('User changes:', changes);
  // Will receive: { name: 'Bob' } or { preferences: { theme: 'light' } }
});

// Only notified when settings change
LazyWatch.on(app.settings, changes => {
  console.log('Settings changes:', changes);
  // Will receive: { lang: 'fr' }
});

app.user.name = 'Bob';      // Only user listener fires
app.settings.lang = 'fr';   // Only settings listener fires

Removing Listeners

LazyWatch.off(watchedObject, callback);

Removes a previously registered callback function.

Pausing and Resuming Event Emissions

LazyWatch.pause(watchedObject);

Pauses event emissions. Changes continue to be tracked but listeners won't be notified until resume() is called.

LazyWatch.resume(watchedObject);

Resumes event emissions. If there are pending changes, they will be emitted immediately.

const isPaused = LazyWatch.isPaused(watchedObject);

Returns true if the watched object is currently paused, false otherwise.

Example:

const data = new LazyWatch({ count: 0 });

LazyWatch.on(data, diff => {
  console.log('Changes:', diff);
});

LazyWatch.pause(data);
data.count = 1;
data.count = 2;
data.count = 3;
// No listener notifications while paused

LazyWatch.resume(data);
// Immediately logs: Changes: { count: 3 }

Silent Mutations

const diff = LazyWatch.silent(watchedObject, callback);

Executes a callback while suppressing event emissions. Any changes made during the callback are tracked and returned as a diff object. Forces emission of any pending changes before silent execution to ensure a clean slate.

Parameters:

  • watchedObject - The LazyWatch proxy
  • callback - Function to execute silently

Returns:

  • A diff object containing changes made during the callback

Example:

const data = new LazyWatch({ count: 0, name: '' });

LazyWatch.on(data, diff => {
  console.log('Changes:', diff);
});

// Make silent changes without triggering listeners
const diff = LazyWatch.silent(data, () => {
  data.count = 1;
  data.name = 'test';
});

// diff = { count: 1, name: 'test' }
// No listener was triggered

// Use the returned diff to perform custom operations
console.log('Silent changes:', diff);

Use cases:

  • Initializing state without triggering listeners
  • Bulk updates where you want manual control over notifications
  • Testing or debugging scenarios where you need to inspect changes without side effects

Applying Changes

Patching LazyWatch Proxies

LazyWatch.patch(watchedObject, diffObject);

Applies changes from a diff object to a watched LazyWatch proxy. Properties not present in the diff are preserved (merge behavior, not replacement).

Example:

const data = new LazyWatch({ a: 1, b: 2, c: { d: 3 } });

LazyWatch.patch(data, { a: 10, c: { d: 30, e: 40 } });
// Result: { a: 10, b: 2, c: { d: 30, e: 40 } }
// Note: 'b' is preserved, nested object 'c' is merged

Patching Normal Objects

LazyWatch.patchObject(targetObject, sourceObject);

Applies changes from a source object to a normal (non-proxy) object. This is useful when you want to use LazyWatch's patching semantics on regular objects without creating a watched proxy.

Parameters:

  • targetObject - A normal object or array (not a LazyWatch proxy)
  • sourceObject - The object with values to merge into the target

Behavior:

  • Merges properties from source into target (mutates target in place)
  • Missing properties in source are preserved in target
  • Nested objects are recursively merged
  • Properties with null values are deleted from target
  • Objects/arrays are deep cloned to avoid reference sharing

Example:

const normalObj = { a: 1, b: 2, c: { d: 3 } };

LazyWatch.patchObject(normalObj, { a: 10, c: { d: 30, e: 40 } });
// normalObj is now: { a: 10, b: 2, c: { d: 30, e: 40 } }

// Using null to delete properties
const obj2 = { a: 1, b: 2, c: 3 };
LazyWatch.patchObject(obj2, { b: null, c: 30 });
// obj2 is now: { a: 1, c: 30 }

Use cases:

  • Applying server-side state updates to local objects
  • Merging configuration objects
  • Synchronizing state between watched and non-watched objects

Examples

💡 Looking for more examples? Check out EXAMPLES.md for comprehensive real-world use cases including state management, undo/redo systems, form validation, and more advanced patterns.

Basic Object Watching

const user = new LazyWatch({ name: 'John', age: 30 });

LazyWatch.on(user, diff => {
  console.log('User changed:', diff);
});

user.name = 'Jane';
user.age = 31;
// After the next tick, logs: User changed: { name: 'Jane', age: 31 }

Nested Objects

const data = new LazyWatch({
  user: {
    profile: {
      name: 'John',
      settings: {
        theme: 'dark'
      }
    }
  }
});

LazyWatch.on(data, diff => {
  console.log('Data changed:', diff);
});

data.user.profile.settings.theme = 'light';
// After the next tick, logs: Data changed: { user: { profile: { settings: { theme: 'light' } } } }

Working with Arrays

const list = new LazyWatch({ items: [1, 2, 3] });

LazyWatch.on(list, diff => {
  console.log('List changed:', diff);
});

list.items.push(4);
list.items[0] = 10;
// After the next tick, logs: List changed: { items: { 0: 10, 3: 4, length: 4 } }

Syncing Objects

const source = new LazyWatch({ a: 1, b: 2, c: { d: 3 } });
const target = new LazyWatch({ a: 0, b: 0, c: { d: 0 } });

LazyWatch.on(source, diff => {
  // Apply changes from source to target
  LazyWatch.patch(target, diff);
  console.log('Target updated:', target);
});

source.a = 10;
source.c.d = 30;
// After the next tick:
// 1. Logs the diff: { a: 10, c: { d: 30 } }
// 2. Patches target
// 3. Logs: Target updated: { a: 10, b: 2, c: { d: 30 } }

Deleting Properties

const obj = new LazyWatch({ a: 1, b: 2, c: 3 });

LazyWatch.on(obj, diff => {
  console.log('Object changed:', diff);
});

delete obj.b;
// After the next tick, logs: Object changed: { b: null }

Advanced Example

const initialData = () => {
  return { pretty: false, list: [{ nice: false }], right: true, junk: 123 };
};

// Create two instances with the same initial data
const UI = new LazyWatch(initialData());
const mirror = new LazyWatch(initialData());

// Define a change listener that will sync changes to the mirror
const changeListener = diff => {
  console.log('Changes detected:', diff);
  // Apply the changes to the mirror object
  LazyWatch.patch(mirror, diff);
  console.log('Mirror updated:', mirror);
};

// Register the change listener
LazyWatch.on(UI, changeListener);

// Make multiple changes
UI.pretty = true;
UI.list[0].nice = true;
delete UI.junk;

// After the next tick, all changes will be batched into a single update

How It Works

LazyWatch uses JavaScript Proxies to intercept property access, assignment, and deletion operations. When changes are detected, they are collected into a diff object. Using queueMicrotask, these changes are then emitted asynchronously in the next microtask, allowing multiple changes to be batched together.

Testing

To run the tests:

npm test

This will execute the test suite using a custom test runner, which verifies the functionality of LazyWatch including object creation, change detection, event emission, and patching.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  • Fork the repository
  • Create your feature branch (git checkout -b feature/amazing-feature)
  • Commit your changes (git commit -m 'Add some amazing feature')
  • Push to the branch (git push origin feature/amazing-feature)
  • Open a Pull Request

License

This project is licensed under the ISC License - see the LICENSE file for details.

Repository

GitHub Repository

FAQs

Package last updated on 03 Apr 2026

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts