Rules Hub
Coding Rules Library
Rule priority, scope & exceptions
Use this to align rules with the senior-level structure (P0/P1/P2, scope, exceptions/tradeoffs).
Scope MutationObserver to the specific attribute you care about
Use attributeFilter (and the minimal set of observe options) so a MutationObserver only fires for the changes you actually care about.
Bad example
| 1 | const observer = new MutationObserver(() => { |
| 2 | // fires for childList, every attribute, text changes... |
| 3 | reactToStyleChange(); |
| 4 | }); |
| 5 | observer.observe(node, { |
| 6 | childList: true, |
| 7 | attributes: true, |
| 8 | subtree: true, |
| 9 | }); |
Explanation (EN)
Observing childList plus all attributes means the callback runs on changes you do not care about, forcing the callback to re-filter and obscuring what is actually being watched.
Objašnjenje (HR)
Promatranje childList i svih atributa znači da se callback poziva i na promjene koje te ne zanimaju, pa callback mora ponovno filtrirati i nije jasno što se zapravo prati.
Good example
| 1 | const observer = new MutationObserver((mutations) => { |
| 2 | // only style-attribute mutations reach here |
| 3 | reactToStyleChange(mutations); |
| 4 | }); |
| 5 | observer.observe(node, { |
| 6 | attributeFilter: ['style'], |
| 7 | attributeOldValue: true, |
| 8 | subtree: true, |
| 9 | }); |
Explanation (EN)
attributeFilter restricts the observer to the single attribute that matters, so the callback only runs for relevant mutations and the observed scope is self-documenting.
Objašnjenje (HR)
attributeFilter ograničava promatrača na jedini atribut koji je bitan, pa se callback poziva samo na relevantne promjene, a opseg promatranja je sam po sebi dokumentiran.
Notes (EN)
Setting attributeOldValue: true also gives you mutation.oldValue so you can compare the previous and current value inside the callback.
Bilješke (HR)
Postavljanje attributeOldValue: true daje ti i mutation.oldValue pa unutar callbacka možeš usporediti prijašnju i trenutnu vrijednost.
Exceptions / Tradeoffs (EN)
When you genuinely need to react to several attributes or to childList/text changes, observe all of them; the point is to observe only what you actually use.
Iznimke / Tradeoffi (HR)
Kada stvarno trebaš reagirati na više atributa ili na childList/text promjene, promatraj sve njih; poanta je promatrati samo ono što stvarno koristiš.