Files
owl/examples/todoapp/store.js
T

76 lines
2.2 KiB
JavaScript
Raw Normal View History

2019-03-19 14:10:05 +01:00
//------------------------------------------------------------------------------
// ACTIONS
//------------------------------------------------------------------------------
const actions = {
2019-03-20 13:36:37 +01:00
addTodo({ commit }, title) {
commit("addTodo", title);
2019-03-19 14:10:05 +01:00
},
removeTodo({ commit }, id) {
commit("removeTodo", id);
},
toggleTodo({ state, commit }, id) {
const todo = state.todos.find(t => t.id === id);
2019-03-20 13:36:37 +01:00
commit("editTodo", { id, completed: !todo.completed });
2019-03-19 14:10:05 +01:00
},
clearCompleted({ state, commit }) {
state.todos
2019-03-20 13:36:37 +01:00
.filter(todo => todo.completed)
2019-03-19 14:10:05 +01:00
.forEach(todo => {
commit("removeTodo", todo.id);
});
},
2019-03-20 13:36:37 +01:00
toggleAll({ state, commit }, completed) {
2019-03-19 14:10:05 +01:00
state.todos.forEach(todo => {
2019-03-20 13:36:37 +01:00
commit("editTodo", { id: todo.id, completed });
2019-03-19 14:10:05 +01:00
});
2019-03-20 13:36:37 +01:00
},
editTodo({ commit }, { id, title }) {
commit("editTodo", { id, title });
2019-03-19 14:10:05 +01:00
}
};
//------------------------------------------------------------------------------
// MUTATIONS
//------------------------------------------------------------------------------
const mutations = {
2019-03-20 13:36:37 +01:00
addTodo(state, title) {
2019-03-19 14:10:05 +01:00
const id = state.nextId++;
2019-03-20 13:36:37 +01:00
const todo = { id, title, completed: false };
2019-03-19 14:10:05 +01:00
state.todos.push(todo);
},
removeTodo(state, id) {
const index = state.todos.findIndex(t => t.id === id);
state.todos.splice(index, 1);
},
2019-03-20 13:36:37 +01:00
editTodo(state, { id, title, completed }) {
2019-03-19 14:10:05 +01:00
const todo = state.todos.find(t => t.id === id);
2019-03-20 13:36:37 +01:00
if (title !== undefined) {
todo.title = title;
2019-03-19 14:10:05 +01:00
}
2019-03-20 13:36:37 +01:00
if (completed !== undefined) {
todo.completed = completed;
2019-03-19 14:10:05 +01:00
}
}
};
2019-03-20 13:36:37 +01:00
//------------------------------------------------------------------------------
// STORE
//------------------------------------------------------------------------------
const LOCALSTORAGE_KEY = "todos-odoo";
2019-03-19 14:10:05 +01:00
export function makeStore() {
2019-03-20 13:36:37 +01:00
const todos = JSON.parse(
window.localStorage.getItem(LOCALSTORAGE_KEY) || "[]"
);
2019-03-19 14:10:05 +01:00
const nextId = Math.max(0, ...todos.map(t => t.id || 0)) + 1;
const state = { todos, nextId };
2019-03-20 13:36:37 +01:00
const store = new odoo.core.Store({ state, actions, mutations });
store.on("update", null, () => {
const state = JSON.stringify(store.state.todos);
window.localStorage.setItem(LOCALSTORAGE_KEY, state);
});
return store;
2019-03-19 14:10:05 +01:00
}