From 6d60dcb99c4e53a8c93604d94fa16de9cc9c4aa8 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Tue, 16 Jan 2018 15:57:40 +0200 Subject: [PATCH] Update observeMutations.md --- snippets/observeMutations.md | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/snippets/observeMutations.md b/snippets/observeMutations.md index d78e5cc39..7af06f90c 100644 --- a/snippets/observeMutations.md +++ b/snippets/observeMutations.md @@ -1,23 +1,27 @@ ### observeMutations -Runs the provided callback for each mutation on the specified element. +Returns a new MutationObserver and runs the provided callback for each mutation on the specified element. Use a [`MutationObserver`](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) to observe mutations on the given element. Use `Array.forEach()` to run the callback for each mutation that is observed. Omit the third argument, `options`, to use the default [options](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver#MutationObserverInit) (all `true`). ```js -const observeMutations = (element, callback, options) => new MutationObserver(mutations => mutations.forEach(m => callback(m))).observe(element, Object.assign( - { +const observeMutations = (element, callback, options) => { + const observer = new MutationObserver(mutations => mutations.forEach(m => callback(m))); + observer.observe(element, Object.assign({ childList: true, attributes: true, attributeOldValue: true, characterData: true, characterDataOldValue: true, subtree: true - }, options)); + }, options)); + return observer; +} ``` ```js -observeMutations(document, console.log); // Logs all mutations that happen on the page +const obs = observeMutations(document, console.log); // Logs all mutations that happen on the page +obs.disconnect(); // Disconnects the observer and stops logging mutations on the page ```