Registers a function to be called when the given element is destroyed.
Elements are destroyed when they are swapped during render pass, when their layer
closes, or when up.destroy()
is called on the element or its container.
An alternative way to register a destructor function is to return it from your compiler function.
The code below will log a message when element
exits the DOM:
let element = document.querySelector('.element')
up.destructor(element, () => console.log('Element was destroyed!'))
The element should be attached when the destructor is registered. This is commonly done during compilation.
If called on a detached element Unpoly assumes an async compiler has registered the destructor after the element has been destroyed. The destructor is then run immediately.
You may reuse the same destructor function for multiple element. The destructor function is called with the element being destroyed:
let fn = (element) => console.log('Element %o was destroyed', element)
for (let element of document.querySelector('div')) {
up.destructor(fn)
}