- From: Lcf.vs <notifications@github.com>
- Date: Sun, 26 Sep 2021 01:19:15 -0700
- To: whatwg/dom <dom@noreply.github.com>
- Cc: Subscribed <subscribed@noreply.github.com>
- Message-ID: <whatwg/dom/issues/1019@github.com>
Hi all,
I would like to suggest an improvement on the `MutationObserver`.
## Motivations
Imho, the current implemetation has a problem increasing the code complexity: the need of to treat the mutations in a callback.
Depending on the strategies...
* it can enforce to wrap all the behaviors in a same function
* it can enforce to mutate something external written by the developer to manage the mutations externally (disallowing the immutable stategies on that management)
* it can complicate the treatment for a specific target
## The suggested improvement
An idea I implemented to simplify the behavior is to turn the observer as an iterable.
My approach, to see the suggested behavior:
```js
export class MutationObserver extends globalThis.MutationObserver {
#wait = resolve => this.#resolve = resolve
#register = () => this.#promises.push(new Promise(this.#wait))
#records = []
#resolve = null
#promises = []
constructor (callback = null) {
super(records => {
this.#record.push(...records)
this.#resolve?.()
this.#register()
callback?.(records, this)
})
this.#register()
}
disconnect () {
this.#resolve()
super.disconnect()
}
async* [Symbol.asyncIterator] () {
let index = 0
for (const promise of this.#promises) {
await promise
for (; index < this.#records.length; index += 1) {
yield this.#records[index]
}
}
}
}
```
## Usage
```js
const frag = document.createDocumentFragment()
const append = () => frag.append(document.createElement('div'))
const observer = new MutationObserver()
observer.observe(frag, {
childList: true
})
append()
append()
setTimeout(append, 1000)
setTimeout(() => observer.disconnect(), 3000)
setTimeout(append, 4000) // not observed
for await (const mutations of observer) {
console.log(mutations)
}
for await (const mutations of observer) {
console.log(mutations)
}
console.log('end')
```
Any thoughts about it, please?
--
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/whatwg/dom/issues/1019
Received on Sunday, 26 September 2021 08:19:28 UTC