choojs / choojs/choo

Create element with own state/context

Open
#502 3 comments 0 reactions 0 assignees View on GitHub
Type: Question
Dominant language
JavaScript
Stars
6.8k
Forks
573
PR merge metrics
No merged PRs in 30d

Description

I am trying to create a TODO app with more than 1 TODO component in the same page, but without using an `array.map(...)`.

I'd like to create the component with it's own `state`, so I can have one TODO with a list and the other with another list. I am trying something like this:

```


${todoList(state, emit)}
${todoList(state, emit)}
${todoList(state, emit)}

```

How can I achieve this?
When I create it like this they are all sharing the same state. I tried creating a property `todoList` in `state` and `push` the instances there, but I couldn't think of a way to identify what is the first time the element is created and what is a dynamic `render` event, so I was triggering only the first `addState` call.

```
let firstAccess = true;
let thisState;
const componentName = 'todoList';

function initialize(state, emitter) {
const initialized = addState(componentName, initialState, state);
firstAccess = false;
thisState = initialized;
eventListeners(thisState, emitter);
}

export default (state, emit, emitter) => {
if (firstAccess) initialize(state, emitter);
[...]
```
I could use the `DOMContentLoaded` event, but what if I insert the element dynamically later?

My code is here, if you want to take a look:
https://github.com/jpenna/todo_choo

--------------------------------
EDIT: Basically, what I want is to initialize the state inside the component (not in the `app` instance), but when I do this I reset the state.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.