Leaf Lifecycle
In the DOM, all elements have a lifecycle, from their initial appearance to their disappearance and subsequent garbage collection. Leaf handles this automatically internally, but there are some cases where you need to remove the side effects generated by the element yourself. In Leaf, we have the connect() and disconnect() functions.
connect()
connect() is useful for triggering side effects when connecting to a DOM element. Simply put, connect() is the best place to initialize setup. It’s typically useful for fetching data from an API when an element appears, initializing a third-party library, or initial styling like dark mode.
Example
defineScope("any", ({ targets }) => {
const hello = targets.hello
function connect() {
const savedTheme = localStorage.getItem("theme")
if (savedTheme === "dark") {
hello.classList.add("dark-mode")
}
}
return { connect }
})
connect() will run automatically when the element (which uses data-scope) appears in the DOM without having to go through data-action.
disconnect()
If connect() is initialization, then disconnect() is for destroying a side effect when an element disappears from the DOM. A real-world example is when performing a live search using the Leaf.js + Briz.js combination.
Example
defineScope("any", ({ root, targets }) => {
const input = targets.input
let timeout
function search() {
clearTimeout(timeout)
timeout = setTimeout(() => {
root.requestSubmit()
}, 500)
}
function disconnect() {
clearTimeout(timeout)
}
return { search, disconnect }
})
In the code above, disconnect() will run automatically when the element (which uses data-scope) is removed from the DOM.
Prev: APIYou can also use connect() and disconnect() together inside defineScope.