Re: [w3c/webcomponents] How to avoid memory leaks when detecting custom elements? (#674)

What I mean, is suppose `SomeElement` wishes to observe all children, and wants to specifically run logic when one of those children is `instanceof OtherElement`.

Now, imagine that the library author that ships `SomeElement` and `OtherElement` to the end user does not name the element. The library author tells the user

> You can name these elements anything you want.

Then the user does so:

```js
customElements.define('any-thing', SomeElement)
customElements.define('an-element', OtherElement)
```

Then the library author's `SomeElement` will need to have code like the following (based on the above) in order to detect the children and react only to instances of `OtherElement`:

```js
        for (const elm of Array.from(this.children)) {
            if (elm.nodeName.includes('-')) {
                customElements.whenDefined(elm.nodeName.toLowerCase()).then(() => {
                    if (elm instanceof OtherElement) {
                       // do something only if the child is an OtherElement
                    }
                })
            }
        }
```

This is a completely fair thing for a library author to want to do given the API that Custom Elements v1 ships to people (authors and users).

If for some reason, the user's app route changes to some other page, and perhaps the SomeElement is not needed any more, and things weren't done loading, then `SomeElement` might be `disconnected`, and it would be fair to prevent `SomeElement` from running logic for child `OtherElement`s.

There's two things to note:

1. The elm.nodeName might be a name for a future custom element, which will eventually be defined.
2. It might not ever be defined (the web allows us to write elements with any name even if they don't exist, so people _will_ do that sometimes).

In general, we should be able to clean up. I'm sure there's more examples that just this one. f.e., suppose we clean up all the Promises after a few minutes (or seconds) if they are never registered.

Being able to clean up memory is essential for long-running desktop applications. People are making them with Electron...

-- 
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/674#issuecomment-335342496

Received on Tuesday, 10 October 2017 02:37:57 UTC