@chrisburnell/observatory
v1.0.1
Published
A JavaScript Class to simplify managing Mutation Observers.
Downloads
83
Readme
Observatory
A JavaScript Class to simplify managing Mutation Observers.
More detail in this README to come soon!
Installation
You have a few options (choose one of these):
- Install via npm:
npm install @chrisburnell/observatory - Download the source manually from GitHub into your project.
- Skip this step and use the script directly via a 3rd party CDN (not recommended for production use)
Usage
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);API
new Observatory(config)
Properties & Methods
observer.defaultOptions(getter)observer.options(getter/setter)observer.useDefaultOptions(getter/setter)observe()disconnect()takeRecords()
Examples
Watch for added nodes
const watcher = new Observatory({
element: container,
onMutation: (mutations) => {
mutations.forEach(mutation => {
if (mutation.type === "childList") {
console.log("New nodes added:", mutation.addedNodes);
}
});
},
});
watcher.observe();Watch for attribute changes only
const watcher = new Observatory({
element: container,
onMutation: () => console.log("Attribute changed"),
options: { attributes: true },
useDefaultOptions: false,
});
watcher.observe();Extend/Augment into own Class
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;
};
}Notes
- If
optionsoruseDefaultOptionsare updated while observing, Observatory will restart the observer automatically, so there is no need to recallobserve(). onStartis guaranteed to only run once, no matter how many timesobserve()is called.
