cferdinandi / reef

A lightweight library for creating reactive, state-based components and UI.
https://reefjs.com
MIT License
1.16k stars 77 forks source link

[WIP] Optional target element to simplify child components #151

Closed wireless25 closed 2 years ago

wireless25 commented 2 years ago

Hi @cferdinandi

I came across Reef a few weeks ago and I really like working with it. One thing that bugs me though is the fact, that every component needs a target element when initialized. This makes working with child components more complicated than it needs to be.

In cases where a component is used only as a child, its kind of awkward to add an extra wrapper to attach this component to.

// some parent component
import baseButton from './components/baseButton.js'

// ...
template() {
  return `
    <div id="button-wrapper">
      ${baseButton.html()}
    </div>
  `
}

// ...

The target is not even relevant when calling the .html() function. Initialization of a new component is not possible without a target element, but it works with some dummy string, as .html() does not use the element anyway.

// child component

const baseButton = new Reef('definitely-not-a-selector', {
  // ...
})

// some parent component

`${baseButton.html()}` // still works

As a solution, I would propose to make the target element optional upon initialization of a new component. This way child components can be initialized and used much leaner.

// baseButton.js

const baseButton = new Reef(null, {
  // ...
})

// some parent component
import baseButton from './components/baseButton.js'

// ...
template() {
  return `
    <!-- other markup -->
      ${baseButton.html()}
    <!-- other markup -->
  `
}

// ...

only the "main" app component really needs the target, where it should mount to.

EDIT: After digging a little deeper into the source I realized, that the prototype.render() method is called when reactive data of the child changes. The prototype.html() method is only called when the parent components' data changes. Looks like this is not as easy a little change as I thought in the beginning.

Still I think this would be a nice improvement of Reef and worth working on.

wireless25 commented 2 years ago

with V12 this PR is obsolete

cferdinandi commented 2 years ago

Sorry, @wireless25 ! I never noticed this PR. It was a really smart idea, and I'm sorry I never incorporated it into the codebase. 😔