Skip to content

Latest commit

 

History

History
76 lines (63 loc) · 2.76 KB

BauLifecycle.md

File metadata and controls

76 lines (63 loc) · 2.76 KB

Bau Lifecycle Method

Bau provides several lifecycle methods to act upon a DOM element creation and destruction:

  • bauCreated: Called after the element has been created, but before being inserted into the tree. One use case is to overide the innerHTML property of the element, required by some third party libraries such as highlight.js and D3.
  • bauMounted: Called after the element has been added into the tree. At this time, the position and dimensions are known.
  • bauUnmounted: Called when the element is being deleted. It is opportunity to clean up things, and also to eventually for animation purposes. Under the hood, Mutation Observer is created on the parent element which listens for deletion of its child.
  • bauChildMutated: : Called when a child node is being added or removed.
const MyComponent = ({ someData }) =>
  div(
    {
      bauCreated: ({ element }) => {
        element.innerHTML =
          "<div>My stuff from a 3rd party library spitting html string.</div>";
      },
      bauMounted: (/*{ element }*/) => {
        window.addEventListener("scroll", handleScroll);
      },
      bauUnmounted: (/*{ element }*/) => {
        window.removeEventListener("scroll", handleScroll);
      },
      bauChildMutated: ({ record, element }) => {
        [...record.removedNodes].forEach((childNode) => {
          // Handle removed node
        });
        [...record.addedNodes].forEach((childNode) => {
          // Handle added node
        });
      },
    },
    h1("Bau lifecycle methods"),
    p("bauMounted and bauUnmounted")
  );

Scrolling Event example

The following code example listens to the scroll event and store the scrollY property.

The bauMounted and bauUnmounted are invoked when the underlying DOM element has been mounted and unmounted to and from the DOM tree.

import Bau from "@grucloud/bau";
const bau = Bau();
const { div, h1, ul, li } = bau.tags;

const scrollState = bau.state(0);

const handleScroll = (/*event*/) => (scrollState.val = window.scrollY);

const ScrollNumber = () =>
  div({ class: "scroll-number" }, "scroll: ", () => scrollState.val);

const App = () =>
  div(
    h1("Bau Lifecycle methods"),
    div(
      {
        bauMounted: (/*{ element }*/) => {
          window.addEventListener("scroll", handleScroll);
        },
        bauUnmounted: (/*{ element }*/) => {
          window.removeEventListener("scroll", handleScroll);
        },
      },
      ScrollNumber(),
      ul(new Array(1000).fill("").map((_, index) => li("index ", index)))
    )
  );

document.getElementById("app").replaceChildren(App());

Check out the complete scolling example source code