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:
If observers are not unsubscribed, the observable holds references to them — memory leak risk in SPAs
Cascade updates — one observable notifying many observers can cause complex update chains that are hard to trace
No guaranteed delivery order unless explicitly enforced
Debugging is harder than direct calls — add logging in notify() during development
When NOT to use:
When only one consumer exists — a direct callback is simpler
When the update sequence matters and subscribers need to be ordered — use a queue or middleware chain instead
For synchronous, predictable data flow — use signals or reducers
Read the instructions and examples in this document.
Apply the patterns to your implementation, adapting to your specific context.
Verify your implementation against the details and edge cases listed above.
Harness Integration
Type: knowledge — this skill is a reference document, not a procedural workflow.
No tools or state — consumed as context by other skills and agents.
Success Criteria
The patterns described in this document are applied correctly in the implementation.
Edge cases and anti-patterns listed in this document are avoided.
1---2name: js-observer-pattern3description: JS Observer Pattern4metadata:5 source: https://skillmd.com/skills/intense-visions/js-observer-pattern6---7# JS Observer Pattern89> Notify subscribers automatically when an observable object's state changes1011## When to Use1213- Multiple parts of the app need to react to the same event without coupling the emitter to its consumers14- Implementing event systems, reactive UI updates, or real-time data feeds15- Decoupling data sources from their consumers1617## Instructions18191. Create an observable with an `observers` array and `subscribe` / `unsubscribe` / `notify` methods.202. Call `notify(data)` whenever the observable's state changes — it invokes all subscribed callbacks.213. Always provide `unsubscribe` — failing to unsubscribe causes memory leaks in long-lived apps.224. In browser environments, prefer native `EventTarget` or `EventEmitter` (Node.js) over hand-rolled implementations.2324```javascript25class Observable {26 constructor() {27 this.observers = [];28 }2930 subscribe(fn) {31 this.observers.push(fn);32 return () => this.unsubscribe(fn); // return cleanup function33 }3435 unsubscribe(fn) {36 this.observers = this.observers.filter((obs) => obs !== fn);37 }3839 notify(data) {40 this.observers.forEach((fn) => fn(data));41 }42}4344const store = new Observable();45const cleanup = store.subscribe((data) => console.log('Received:', data));46store.notify({ type: 'UPDATE', payload: 42 });47cleanup(); // unsubscribe48```49505. Return a cleanup/unsubscribe function from `subscribe` — consumers call it to remove the handler.5152## Details5354The 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.5556**Trade-offs:**5758- If observers are not unsubscribed, the observable holds references to them — memory leak risk in SPAs59- Cascade updates — one observable notifying many observers can cause complex update chains that are hard to trace60- No guaranteed delivery order unless explicitly enforced61- Debugging is harder than direct calls — add logging in `notify()` during development6263**When NOT to use:**6465- When only one consumer exists — a direct callback is simpler66- When the update sequence matters and subscribers need to be ordered — use a queue or middleware chain instead67- For synchronous, predictable data flow — use signals or reducers6869## Source7071https://patterns.dev/javascript/observer-pattern7273## Process74751. Read the instructions and examples in this document.762. Apply the patterns to your implementation, adapting to your specific context.773. Verify your implementation against the details and edge cases listed above.7879## Harness Integration8081- **Type:** knowledge — this skill is a reference document, not a procedural workflow.82- **No tools or state** — consumed as context by other skills and agents.8384## Success Criteria8586- The patterns described in this document are applied correctly in the implementation.87- Edge cases and anti-patterns listed in this document are avoided.
Run npx get-skill add intense-visions/js-observer-pattern in your terminal (requires Node.js), paste this page's agent-chat prompt into Claude, Cursor, or any MCP-connected agent, or download the SKILL.md file and copy it into your agent's skills directory.
JS Observer Pattern It is listed under Coding & Dev Tools on SkillMD.
This skill has not completed SkillMD's automated safety review yet. Independent scanners report: SkillSpector: PASS, Skill Scanner: PASS. Capability flags: docs only. SkillMD never runs a skill's scripts for you; review the SKILL.md before installing.
This skill is tagged as working with Claude Code, Claude.ai, OpenAI Codex. SKILL.md is an open format, so most agents that read a skills directory can load it too.
Yes. Installing skills from SkillMD is free, and the skill stays under its author's original license.
Intense-Visions (@intense-visions) published this skill. Their other Agent Skills are listed on their SkillMD profile.