К основному содержанию
скилл CX Codex

observer-pattern — скилл для Claude Code: паттерн наблюдателя

Скилл объясняет паттерн наблюдателя и подсказывает агенту, как строить слабосвязанную подписку на события в JS и TS.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add PatternsDev/skills --skill observer-pattern -a claude-code
Открыть на GitHub

Что делает observer-pattern

Скилл учит агента паттерну наблюдателя для событийной связи между частями приложения. Внутри — инструкция, когда паттерн уместен, а когда нет, и разбор из чего состоит observable: массив observers, методы subscribe(), unsubscribe() и notify(). Пример на ES6-классе показывает, как подписать функции-наблюдатели и разослать им данные при событии.

Скилл применяется к файлам **/*.js и **/*.ts. В примерах фигурируют React-компоненты Button и Switch и библиотека react-toastify — логгер и всплывающее уведомление подписываются на observable и срабатывают на клик или переключение. Для продвинутой реактивности автор советует посмотреть в сторону RxJS.

Прямо в инструкции перечислены случаи, когда паттерн брать не стоит: если подписчиков очень много и скорость оповещения критична, если хватает обычного колбэка для связи один-к-одному, если отладка неявных цепочек событий обойдётся дороже, чем выигрыш от развязки. Сложный наблюдатель тоже бьёт по производительности при рассылке всем подписчикам.

Какие задачи решает

  • развязать компоненты, которые должны узнавать об изменении состояния
  • сделать подписку и отписку от событий без жёстких связей
  • разослать одно событие сразу нескольким обработчикам
  • решить, когда паттерн наблюдателя лишний и хватит колбэка
  • оценить риски отладки неявных цепочек событий

Примеры запросов агенту

  • Помоги спроектировать observable с методами subscribe, unsubscribe и notify для моего модуля на TypeScript
  • Нужно, чтобы клик по кнопке и переключение свитча уведомляли логгер и всплывающее уведомление — покажи, как связать их через паттерн наблюдателя
  • Стоит ли здесь брать паттерн наблюдателя или хватит обычного колбэка?

Как установить observer-pattern

1Через Skills CLI (Vercel)

npx skills add PatternsDev/skills --skill observer-pattern -a claude-code

2Вручную: положить файлы

~/.claude/skills/observer-pattern/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/observer-pattern/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Из того же набора44

view-transitions Учит агента работать с View Transitions API: переходы между страницами и состояниями интерфейса браузер анимирует сам. CX Codex +1 678установок vite-bundle-optimization Скилл с паттернами оптимизации бандла и сборки в Vite + React. Пригодится, когда билд тормозит или чанки выходят больше ожидаемого. CX Codex +1 667установок command-pattern Обучает агента паттерну «Команда» для JavaScript и TypeScript. Помогает разделить вызов операции и её выполнение, настроить очередь задач или историю отмены. CX Codex +1 645установок singleton-pattern Обучает реализации паттерна «Одиночка» в JavaScript и TypeScript для создания единого экземпляра класса. Пригодится при настройке общих ресурсов или глобальной конфигурации. CX Codex +1 637установок factory-pattern Учит агента создавать объекты через фабричные функции. Пригодится, когда логика создания объектов зависит от конфигурации или окружения. CX Codex +1 634установок module-pattern Обучает ИИ-агента делить JavaScript и TypeScript на изолированные модули через ES2015. Помогает скрыть внутренние переменные и настроить чистый экспорт. CX Codex +1 631установок islands-architecture Скилл объясняет паттерн островной архитектуры и частичной гидратации. Пригодится, когда страница почти вся статичная, а интерактив нужен точечно. CX Codex +1 624установок provider-pattern Учит агента выносить общие данные в React Context и раздавать их через Provider, когда пропсы приходится тянуть через десяток компонентов. CX Codex +1 620установок

Похожие

nextjs-client-cookie-pattern wsimmonds Скилл показывает, как из клиентского компонента Next.js выставить серверную куку через server action. Пригодится для тем, авторизации и языковых настроек. CX Codex +1 323установок coding-standards affaan-m Базовые правила кода для проектов: проверяет именование, запрещает мутации объектов и следит за простыми конструкциями. Пригодится на ревью и рефакторинге. CX Codex +1 5 700установок typescript-write metabase Скилл для написания и редактирования TypeScript и JavaScript кода с соблюдением стандартов Metabase. Требует строгую типизацию без any и проверку типов перед завершением. CX Codex +1 2 100установок vitest-skill TestMu AI Генерирует юнит-тесты на Vitest для JavaScript и TypeScript проектов. Помогает настроить моки через vi и протестировать компоненты React. CX Codex +1 448установок anime-js Mindrally Скилл задаёт агенту правила работы с Anime.js: таймлайны, stagger, SVG-морфинг и производительность. Пригодится, когда анимации в проекте пишет ИИ. CX Codex +1 736установок react-patterns manutej Скилл с готовыми рецептами React: хуки, композиция компонентов, управление состоянием и борьба с лишними ререндерами. CX Codex +1 471установок

Рядом в теме «Языки программирования»

Все скиллы по теме «Языки программирования» →

Вопросы о observer-pattern

Как установить observer-pattern в Claude?

Выполните npx skills add PatternsDev/skills --skill observer-pattern -a claude-code. Скилл окажется в ~/.claude/skills/observer-pattern/SKILL.md.

Что делает observer-pattern?

Учит агента паттерну наблюдателя для событийной связи: как завести observable, подписать на него наблюдателей и оповестить их при событии. Помогает развязать части приложения, которые реагируют на изменение состояния.

Когда паттерн наблюдателя лучше не использовать?

Скилл прямо перечисляет такие случаи: очень много подписчиков и критичная скорость оповещения, связь один-к-одному, где хватает колбэка, и ситуации, когда отладка неявных цепочек событий перевешивает выигрыш от развязки.

Исходный текст

SKILL.md · MIT
---
name: observer-pattern
description: Teaches the observer pattern for event-driven communication. Use when you need decoupled publish/subscribe behavior where multiple parts of your system react to state changes or events.
paths:
  - "**/*.js"
  - "**/*.ts"
license: MIT
metadata:
  author: patterns.dev
  version: "1.1"
related_skills:
  - "module-pattern"
  - "singleton-pattern"
---

# Observer Pattern

## Table of Contents

- [When to Use](#when-to-use)
- [When NOT to Use](#when-not-to-use)
- [Instructions](#instructions)
- [Details](#details)
- [Source](#source)

With the **observer pattern**, we can _subscribe_ certain objects, the **observers**, to another object, called the **observable**. Whenever an event occurs, the observable notifies all its observers!

## When to Use

- Use this when you need to notify multiple parts of an application about state changes or events
- This is helpful for implementing event-driven, asynchronous communication between components

## When NOT to Use

- When the subscriber count is very high and notification performance becomes critical
- When simpler callbacks or direct function calls suffice for one-to-one communication
- When debugging difficulty from implicit event chains outweighs the decoupling benefit

## Instructions

- Create an Observable class with `subscribe`, `unsubscribe`, and `notify` methods
- Keep observers loosely coupled to the observable for better separation of concerns
- Be mindful of performance when notifying many subscribers with complex logic
- Consider using libraries like RxJS for more advanced reactive programming needs

## Details

An observable object usually contains 3 important parts:

- `observers`: an array of observers that will get notified whenever a specific event occurs
- `subscribe()`: a method in order to add observers to the observers list
- `unsubscribe()`: a method in order to remove observers from the observers list
- `notify()`: a method to notify all observers whenever a specific event occurs

Let's create an observable using an ES6 class:

```js
class Observable {
  constructor() {
    this.observers = [];
  }

  subscribe(func) {
    this.observers.push(func);
  }

  unsubscribe(func) {
    this.observers = this.observers.filter((observer) => observer !== func);
  }

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

We can now add observers to the list of observers with the subscribe method, remove the observers with the unsubscribe method, and notify all subscribers with the notify method.

Let's build something with this observable. We have a very basic app that only consists of two components: a `Button`, and a `Switch`.

```js
export default function App() {
  return (
    <div className="App">
      <Button>Click me!</Button>
      <FormControlLabel control={<Switch />} />
    </div>
  );
}
```

We want to keep track of the **user interaction** with the application. Whenever a user either clicks the button or toggles the switch, we want to log this event with the timestamp. Besides logging it, we also want to create a toast notification that shows up whenever an event occurs!

Whenever the user invokes the `handleClick` or `handleToggle` function, the functions invoke the `notify` method on the observer. The `notify` method notifies all subscribers with the data that was passed by the `handleClick` or `handleToggle` function!

First, let's create the `logger` and `toastify` functions. These functions will eventually receive `data` from the `notify` method.

```js
import { ToastContainer, toast } from "react-toastify";

function logger(data) {
  console.log(`${Date.now()} ${data}`);
}

function toastify(data) {
  toast(data);
}

export default function App() {
  return (
    <div className="App">
      <Button>Click me!</Button>
      <FormControlLabel control={<Switch />} />
      <ToastContainer />
    </div>
  );
}
```

Currently, the `logger` and `toastify` functions are unaware of observable: the observable can't notify them yet! In order to make them observers, we'd have to _subscribe_ them, using the `subscribe` method on the observable!

```js
import { ToastContainer, toast } from "react-toastify";

function logger(data) {
  console.log(`${Date.now()} ${data}`);
}

function toastify(data) {
  toast(data);
}

observable.subscribe(logger);
observable.subscribe(toastify);

export default function App() {
  return (
    <div className="App">
      <Button>Click me!</Button>
      <FormControlLabel control={<Switch />} />
      <ToastContainer />
    </div>
  );
}
```

Whenever an event occurs, the `logger` and `toastify` functions will get notified. Now we just need to implement the functions that actually notify the observable: the `handleClick` and `handleToggle` functions! These functions should invoke the `notify` method on the observable, and pass the data that the observers should receive.

```js
import { ToastContainer, toast } from "react-toastify";

function logger(data) {
  console.log(`${Date.now()} ${data}`);
}

function toastify(data) {
  toast(data);
}

observable.subscribe(logger);
observable.subscribe(toastify);

export default function App() {
  function handleClick() {
    observable.notify("User clicked button!");
  }

  function handleToggle() {
    observable.notify("User toggled switch!");
  }

  return (
    <div className="App">
      <Button>Click me!</Button>
      <FormControlLabel control={<Switch />} />
      <ToastContainer />
    </div>
  );
}
```

We just finished the entire flow: `handleClick` and `handleToggle` invoke the `notify` method on the observer with the data, after which the observer notifies the subscribers: the `logger` and `toastify` functions in this case.

Whenever a user interacts with either of the components, both the `logger` and the `toastify` functions will get notified with the data that we passed to the `notify` method!

Although we can use the observer pattern in many ways, it can be very useful when working with **asynchronous, event-based data**. Maybe you want certain components to get notified whenever certain data has finished downloading, or whenever users sent new messages to a message board and all other members should get notified.

### Case study

A popular library that uses the observable pattern is RxJS. RxJS has tons of built-in features and examples that work with the observable pattern.

### Pros

Using the observer pattern is a great way to enforce separation of concerns and the single-responsibility principle. The observer objects aren't tightly coupled to the observable object, and can be (de)coupled at any time. The observable object is responsible for monitoring the events, while the observers simply handle the received data.

### Cons

If an observer becomes too complex, it may cause performance issues when notifying all subscribers.

## Source

- [patterns.dev/vanilla/observer-pattern](https://patterns.dev/vanilla/observer-pattern)

### References

- [RxJS](https://rxjs-dev.firebaseapp.com)
- [JavaScript Design Patterns: The Observer Pattern](https://www.sitepoint.com/javascript-design-patterns-observer-pattern)

© patterns.dev · MIT · PatternsDev/skills

Смотрите также

Спонсоры проекта

Компании, которые помогают держать аналитику открытой