A JavaScript Class to simplify managing Mutation Observers.
npm install @chrisburnell/observatoryA JavaScript Class to simplify managing Mutation Observers.
More detail in this README to come soon!
You have a few options (choose one of these):
1. Install via npm: npm install @chrisburnell/observatory
1. Download the source manually from GitHub into your project.
1. Skip this step and use the script directly via a 3rd party CDN (not recommended for production use)
``javascript
import Observatory from "./observatory.js";
// Target element
const container = document.getElementById("container");
// Create a new Observatory instance
const watcher = new Observatory({
element: container,
onMutation: (mutations, observer) => {
console.log("DOM changed inside container", mutations);
},
onStart: () => {
console.log("Observation started!");
},
});
// Begin observing
watcher.observe();
// Dynamically update options (triggers re-observe)
watcher.options = {
attributes: true,
};
// Stop observing
watcher.disconnect();
// Get any pending mutation records
const records = watcher.takeRecords();
console.log(records);
`
new Observatory(config)
| Property | Type | Description |
|---|---|---|
element | HTMLElement | The DOM element you want to observe (required). |
onMutation | (mutations, observer, instance) => void | Callback function when mutations occur (required). |
onStart | (instance) => void | Optional callback function when observation begins. |
options | object | Optional MutationObserver options. |
useDefaultOptions | boolean | Merge options with default options (childList: true, subtree: true). Default true. |
startImmediately | boolean | Start observing immediately. Default false. |
- observer.defaultOptions (getter)observer.options
- (getter/setter)observer.useDefaultOptions
- (getter/setter)observe()
- disconnect()
- takeRecords()
-
`javascript`
const watcher = new Observatory({
element: container,
onMutation: (mutations) => {
mutations.forEach(mutation => {
if (mutation.type === "childList") {
console.log("New nodes added:", mutation.addedNodes);
}
});
},
});
watcher.observe();
`javascript`
const watcher = new Observatory({
element: container,
onMutation: () => console.log("Attribute changed"),
options: { attributes: true },
useDefaultOptions: false,
});
watcher.observe();
`javascript
import Observatory from "@chrisburnell/observatory";
export default class MyOwnObservatory {
constructor() {
super({
element: container,
options: {
characterData: true,
attributes: true,
}
});
}
this.mySpecialVariable;
this.onMutation = (mutations, observer, instance) => {
this.mySpecialVariable = instance.element.innerText;
};
}
`
- If options or useDefaultOptions are updated while observing, Observatory will restart the observer automatically, so there is no need to recall observe().onStart
- is guaranteed to only run once, no matter how many times observe()` is called.