empty error now managed via store.
h3rald h3rald@h3rald.com
Sat, 11 Apr 2020 11:37:11 +0200
4 files changed,
35 insertions(+),
9 deletions(-)
M
example/assets/js/app.js
→
example/assets/js/app.js
@@ -3,6 +3,7 @@ import AddTodoForm from "./components/addTodoForm.js";
import EmptyTodoError from "./components/emptyTodoError.js"; import NavigationBar from "./components/navigationBar.js"; import TodoList from "./components/todoList.js"; +import store from "./store.js"; // Main application state let todos = [];@@ -14,15 +15,15 @@ let page = 1;
// UI Methods // Add a todo item -const addTodo = (updateError) => { +const addTodo = () => { const newTodo = document.getElementById("new-todo"); if (!newTodo.value) { - displayEmptyTodoError = true; - updateError(); + store.dispatch('emptyTodoError.set'); + store.dispatch('emptyTodoError.update'); document.getElementById("new-todo").focus(); return; } - displayEmptyTodoError = false; + store.dispatch('emptyTodoError.clear'); todos.unshift({ key: `todo_${Date.now()}__${newTodo.value}`, // Make todos "unique-enough" to ensure they are processed correctly text: newTodo.value,@@ -89,7 +90,8 @@ total: filteredTodos.length,
}; const start = (page - 1) * pagesize; const end = Math.min(start + pagesize, filteredTodos.length); - const [error, updateError] = region(() => EmptyTodoError({ displayEmptyTodoError }, { clearError })) + const [error, updateError] = region(() => EmptyTodoError()) + store.on("emptyTodoError.update", updateError); return h3("div#todolist.todo-list-container", [ h3("h1", "To Do List"), AddTodoForm({ addTodo, addTodoOnEnter, updateError }),
M
example/assets/js/components/emptyTodoError.js
→
example/assets/js/components/emptyTodoError.js
@@ -1,9 +1,12 @@
import h3 from "../h3.js"; +import store from "../store.js"; export default function EmptyTodoError(data, actions) { - const { clearError } = actions; - const { displayEmptyTodoError } = data; - const emptyTodoErrorClass = displayEmptyTodoError ? "" : ".hidden"; + const emptyTodoErrorClass = store.get('displayEmptyTodoError') ? "" : ".hidden"; + const clearError = () => { + store.dispatch('emptyTodoError.clear'); + store.dispatch('emptyTodoError.update'); + } return h3(`div#empty-todo-error.error${emptyTodoErrorClass}`, [ h3("span.error-message", ["Please enter a non-empty todo item."]), h3(
A
example/assets/js/store.js
@@ -0,0 +1,21 @@
+import { createStore } from "./h3.js"; + +const todos = (store) => { + store.on("init", () => ({ todos: [], filteredTodos: [], filter: "" })); +}; + +const flags = (store) => { + store.on("init", () => ({ displayEmptyTodoError: false })); + store.on("emptyTodoError.clear", (state) => ({ displayEmptyTodoError: false })); + store.on("emptyTodoError.set", (state) => ({ displayEmptyTodoError: true })); +}; + +const pages = (store) => { + store.on("init", () => ({ pagesize: 10, page: 1 })); +}; + +const store = createStore([todos, flags, pages]); + +store.dispatch("init"); + +export default store;