Js observer pattern

From Intense-Visions/harness-engineering · View interactive version

Js observer pattern is an AI agent skill from the GitHub repository Intense-Visions/harness-engineering. > Notify subscribers automatically when an observable object's state changes

How to use this skill

Skill file

JS Observer Pattern

Notify subscribers automatically when an observable object's state changes

When to Use

Instructions

  1. Create an observable with an observers array and subscribe / unsubscribe / notify methods.
  2. Call notify(data) whenever the observable's state changes — it invokes all subscribed callbacks.
  3. Always provide unsubscribe — failing to unsubscribe causes memory leaks in long-lived apps.
  4. In browser environments, prefer native EventTarget or EventEmitter (Node.js) over hand-rolled implementations.
class Observable {
  constructor() {
    this.observers = [];
  }

  subscribe(fn) {
    this.observers.push(fn);
    return () => this.unsubscribe(fn); // return cleanup function
  }

  unsubscribe(fn) {
    this.observers = this.observers.filter((obs) => obs !== fn);
  }

  notify(data) {
    this.observers.forEach((fn) => fn(data));
  }
}

const store = new Observable();
const cleanup = store.subscribe((data) => console.log('Received:', data));
store.notify({ type: 'UPDATE', payload: 42 });
cleanup(); // unsubscribe
  1. Return a cleanup/unsubscribe function from subscribe — consumers call it to remove the handler.

Details

The Observer pattern (also called pub/sub) separates the emitter (subject/observable) from its consumers (observers/subscribers). This decoupling is fundamental to event-driven architectures, reactive state systems, and streams.

Trade-offs:

When NOT to use:

Source

https://patterns.dev/javascript/observer-pattern

Process

  1. Read the instructions and examples in this document.
  2. Apply the patterns to your implementation, adapting to your specific context.
  3. Verify your implementation against the details and edge cases listed above.

Harness Integration

Success Criteria

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.