Skip to content

Instantly share code, notes, and snippets.

@jaylandro
Created March 10, 2021 06:42
Show Gist options
  • Save jaylandro/2fe6bd057a6535a53c5381af945ab31b to your computer and use it in GitHub Desktop.
Save jaylandro/2fe6bd057a6535a53c5381af945ab31b to your computer and use it in GitHub Desktop.
Super minimal state w/ proxy
window.subscribers = [];
const defaultState = {
todos: []
};
const state = new Proxy(defaultState, {
set(state, key, value) {
const oldState = { ...state };
state[key] = value;
window.subscribers.forEach((callback) => callback(state, oldState));
return state;
}
});
function addTodo() {
event.preventDefault();
const todoForm = document.getElementById("todo-form");
const formData = new FormData(todoForm);
const todo = formData.get("todo-text");
todoForm.reset();
state.todos = [...state.todos, todo];
}
function renderTodos(currentState, oldState = null) {
const todoList = document.getElementById("list");
if (oldState && oldState.todos === currentState.todos) {
return;
}
todoList.innerHTML = state.todos
.map(
(todo, i) => `<li>
<input type="checkbox" id="a${i}" value="done">
<label for="a${i}">${todo}</label>
</li>`
)
.join("");
}
window.subscribers.push(renderTodos);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment