This repository has been archived by the owner on May 13, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
/
TodoApp.js
110 lines (93 loc) · 2.74 KB
/
TodoApp.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
var EventEmitter = require('events');
var nextId = 0;
/**
* This is the "class" definition for our Todo app. On the client-side
* we create a single instance of this class and use it as the default
* exports for the "src/app/todo.js" module. The TodoApp instances
* expose methods can be used to modify the internal application state.
* When the internal state is changed, a "change" event is emitted
* along with the new state.
*
* The TodoApp constructor should be provided with an object with the
* initial state. The provided state object is wrapped and normalized
* by the TodoAppState module.
*
* @param {Object} state The initial state for the todo app.
*/
class TodoApp extends EventEmitter {
constructor() {
super();
this._todos = [];
this._filter = 'all';
}
set todos(newTodos) {
this._todos = newTodos;
this._emitChange();
}
get todos() {
return this._todos;
}
set filter(newFilter) {
if (this._filter === newFilter) {
return;
}
this._filter = newFilter;
this._emitChange();
}
get filter() {
return this._filter;
}
_emitChange() {
this.emit('change', {
todos: this.todos,
filter: this.filter
});
}
/**
* Private method for committing the changes to a todo item by
* making a service call to the backend.
*
* @param {Object} todo The todo item to update on the backend
*/
updateTodo(todoId, newProps) {
this.todos = this.todos.slice(0);
for (var i=0; i<this.todos.length; i++) {
var todo = this.todos[i];
if (todo.id === todoId) {
var newTodo = Object.assign({}, todo, newProps);
this.todos[i] = newTodo;
break;
}
}
}
clearCompleted() {
this.todos = this.todos.filter((todo) => {
return todo.completed === true ? false : true;
});
}
setTodoCompleted(todoId, completed) {
this.updateTodo(todoId, { completed: completed });
}
removeTodo(todoId) {
this.todos = this.todos.filter((todo) => {
return todo.id === todoId ? false : true;
});
}
toggleAllTodosCompleted(completed) {
this.todos = this.todos.map((todo) => {
if (todo.completed === completed) {
return todo;
} else {
return Object.assign({}, todo, { completed: completed });
}
});
}
addNewTodo(todoData) {
this.todos = this.todos.concat({
title: todoData.title,
id: 'c' + (nextId++),
completed: false
});
}
}
module.exports = TodoApp;