jorgebucaran / superfine

Absolutely minimal view layer for building web interfaces
https://git.io/super
MIT License
1.56k stars 78 forks source link

Lifecycle events using Mutation Observer #178

Closed Wildhoney closed 3 years ago

Wildhoney commented 4 years ago

I know #167 was closed because it become too heated, and I don't wish to reignite that discussion.

However I was reaching out to see if you'd be open to adding an example in the README of using MutationObserver to implement the oncreate/ondestroy approach we had with previous versions? As far as I see, the MutationObserver approach is better overall as it's a concern of the DOM rather than superfine.

Essentially:

import { h, patch } from "https://unpkg.com/superfine"

const node = document.getElementById("app")

const callback = function(mutationsList, observer) {
    mutationsList.forEach(mutation => {
        mutation.addedNodes.forEach(node => {
            const event = new CustomEvent('create');
            node.dispatchEvent(event);
        })

        mutation.removedNodes.forEach(node => {
            const event = new CustomEvent('destroy');
            node.dispatchEvent(event);
        })
    })
};

const observer = new MutationObserver(callback);
observer.observe(node, { childList: true });

const setState = state => {
patch(
    node,
    h("div", {}, [
    state >= 0 && h("h1", { oncreate: console.log, ondestroy: console.log}, state),
    h("button", { onclick: () => setState(state - 1) }, "-"),
    h("button", { onclick: () => setState(state + 1) }, "+")
    ])
)
}

setState(0) // Start app with initial state.
jorgebucaran commented 3 years ago

I think we added this at some point, but then I felt it was too distracting to have in the README. This would be great material for a wiki, but I don't have much bandwidth to take care of one in addition to the repository.