| User Manual | API Reference | Blog | Forum |
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.
To install the NPM package, do:
npm install @playcanvas/observer
import { Observer } from '@playcanvas/observer';
const data = {
name: 'John',
age: 30,
address: {
city: 'New York',
zip: '10001'
}
};
const observer = new Observer(data);You can listen for changes to specific properties using the on method:
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 FranciscoCoding agents: start from the PCUI guides index, which covers Observer, and the Observer API index. Both link a Markdown version of every page.
To generate the ESM, CommonJS and UMD builds of the Observer library, along with its type declarations, run:
npm install
npm run build
The ESM build is dist/index.mjs, the CommonJS build is dist/index.cjs and the UMD build is dist/index.js. Type declarations are written to types/.
To build the API reference manual, run:
npm run docs
A pre-built API reference manual is hosted here.