https://github.com/playcanvas/observer
TypeScript implementation of the Observer pattern
https://github.com/playcanvas/observer
observer observer-pattern playcanvas typescript
Last synced: 3 months ago
JSON representation
TypeScript implementation of the Observer pattern
- Host: GitHub
- URL: https://github.com/playcanvas/observer
- Owner: playcanvas
- License: mit
- Created: 2021-08-19T10:05:42.000Z (over 4 years ago)
- Default Branch: main
- Last Pushed: 2025-05-27T14:57:30.000Z (10 months ago)
- Last Synced: 2025-06-19T03:18:15.771Z (9 months ago)
- Topics: observer, observer-pattern, playcanvas, typescript
- Language: TypeScript
- Homepage: https://api.playcanvas.com/observer/
- Size: 560 KB
- Stars: 18
- Watchers: 9
- Forks: 6
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Observer - Observer Pattern for JS/TS
[](https://www.npmjs.com/package/@playcanvas/observer)
[](https://npmtrends.com/@playcanvas/observer)
[](https://github.com/playcanvas/observer/blob/main/LICENSE)
[](https://discord.gg/RSaMRzg)
[](https://www.reddit.com/r/PlayCanvas)
[](https://x.com/intent/follow?screen_name=playcanvas)
| [User Manual](https://developer.playcanvas.com) | [API Reference](https://api.playcanvas.com/observer) | [Blog](https://blog.playcanvas.com) | [Forum](https://forum.playcanvas.com) |
The PlayCanvas Observer is a powerful TypeScript library for managing and observing changes to objects. It allows tracking modifications to nested properties, emitting events on changes, and maintaining state consistency. This is particularly useful in applications where state management and change tracking are critical, such as in data-driven interfaces or collaborative applications.
## Installing
To install the NPM package, do:
```
npm install @playcanvas/observer --save-dev
```
## Usage
### Creating an Observer
```javascript
import Observer from '@playcanvas/observer';
const data = {
name: 'John',
age: 30,
address: {
city: 'New York',
zip: '10001'
}
};
const observer = new Observer(data);
```
### Listening for Changes
You can listen for changes to specific properties using the `on` method:
```javascript
observer.on('address.city:set', (newValue, oldValue) => {
console.log(`City changed from ${oldValue} to ${newValue}`);
});
observer.set('address.city', 'San Francisco'); // Logs: City changed from New York to San Francisco
```
## Building
To generate a UMD and ESM build of the Observer library, run:
```
npm install
npm run build
```
The UMD build is `dist/index.js`. The ESM build is `dist/index.mjs`.
## API Docs
To build the API reference manual, run:
```
npm run docs
```
A pre-built API reference manual is hosted [here](https://api.playcanvas.com/observer/).