The proper way is to use autosize.destroy when an autosize instance is no longer needed.
However, sometimes it may be hard to explicitly destroy existing widget instances. See for this issue from another widget where the DOM element or DOM container element is simply removed. For example, try creating a simple demo page with a div container and some textareas with autosize, then remove the div container from the DOM. The assignedElements still contains all entries, and the memory tab of the dev tools shows many detached DOM elements that weren't garbage collected.
This happens because of 2 reasons: (a) The assignedElements map keeps a hard reference to all DOM textareas and the autosize instances; (b) each instances adds a global resize event listener to the window, and the event listener captures the textarea DOM element with a closure.
There is a simple change that solves these issues:
Use a weak map instead of a map. Supported in all modern browsers, for somewhat older browsers, we can still fall back to a map.
Use a resize observer instead of a global event listener, as already mentioned in the code as a todo. Resize observer won't prevent the observed DOM elements from getting garbage collected. As a bonus, it will now also properly resize when the width is changed in any other. A global resize listener can still be used as a fallback when the environment does not support resize observers.
The proper way is to use
autosize.destroy
when an autosize instance is no longer needed.However, sometimes it may be hard to explicitly destroy existing widget instances. See for this issue from another widget where the DOM element or DOM container element is simply removed. For example, try creating a simple demo page with a div container and some textareas with autosize, then remove the div container from the DOM. The
assignedElements
still contains all entries, and the memory tab of the dev tools shows many detached DOM elements that weren't garbage collected.This happens because of 2 reasons: (a) The
assignedElements
map keeps a hard reference to all DOM textareas and the autosize instances; (b) each instances adds a globalresize
event listener to the window, and the event listener captures the textarea DOM element with a closure.There is a simple change that solves these issues: