Re: [w3c/webcomponents] [idea] childConnectedCallback and childDisconnectedCallback (#550)

> MutationObserver doesn't get invoked until the end of microtask whereas custom element callbacks get invoked almost immediately so it isn't quite polyfillable.

> well, it could but that's undesired, hence my suggestion to use MutationObserver instead (even if not quite the same, I guess it's fine for 99% of use cases)

Actually, I'm running into hitches due to this exact problem, which makes it difficult to coordinate some of my connected/disconnected logic with my polyfill.

For reference, my polyfill looks like this, in my `WebComponent` base class, with code omitted for brevity:

```js
// some code omitted for brevity...

export default
function WebComponentMixin(elementClass) {
    if (!elementClass) elementClass = HTMLElement

    if (!hasHTMLElementPrototype(elementClass)) {
        throw new TypeError(
            'The argument to WebComponentMixin must be a constructor that extends from or is HTMLElement.'
        )
    }

    // some code omitted for brevity...

    // otherwise, create it.
    class WebComponent extends elementClass {

        // constructor() is used in v1 Custom Elements instead of
        // createdCallback() as in v0.
        constructor() {
            super()
            
            // some code omitted for brevity...

            this.createdCallback()
        }

        createdCallback() {
            // some code omitted for brevity...

            const observer = new MutationObserver(changes => {
                for (let change of changes) {
                    if (change.type != 'childList') continue

                    for (let node of change.addedNodes)
                        this.childConnectedCallback(node)

                    for (let node of change.removedNodes)
                        this.childDisconnectedCallback(node)
                }
            })
            observer.observe(this, { childList: true })
        }

        // Subclasses can implement these.
        childConnectedCallback(child) {}
        childDisconnectedCallback(child) {}

        // some code omitted for brevity...
    }
    
    // some code omitted for brevity...

    return WebComponent
}
```

Then, subclasses simply implement the `childConnectedCallback` and `childDisconnectedCallback` methods. But, as mentioned, timing issues happen because the observation does happen in coordination with the connected/disconnected methods, forcing me in some situations to use promises and `await` to coordinate things in a somewhat ugly manner (in my sub classes).

-- 
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/w3c/webcomponents/issues/550#issuecomment-241949288

Received on Wednesday, 24 August 2016 03:42:33 UTC