-
Notifications
You must be signed in to change notification settings - Fork 24
/
todoModel.js
88 lines (72 loc) · 2.19 KB
/
todoModel.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
var app = app || {}
;(function () {
'use strict'
let Utils = app.Utils
// Generic "model" object. You can use whatever
// framework you want. For this application it
// may not even be worth separating this logic
// out, but we do this to demonstrate one way to
// separate out parts of your application.
app.TodoModel = function (key) {
this.key = key
this.todos = Utils.store(key)
this.onChanges = []
}
app.TodoModel.prototype.subscribe = function (onChange) {
this.onChanges.push(onChange)
}
app.TodoModel.prototype.inform = function () {
Utils.store(this.key, this.todos)
this.onChanges.forEach(function (cb) {
cb()
})
}
app.TodoModel.prototype.addTodo = function (...titles) {
titles.forEach(title => {
this.todos = this.todos.concat({
id: Utils.uuid(),
title,
completed: false
})
})
this.inform()
}
app.TodoModel.prototype.toggleAll = function (checked) {
// Note: it's usually better to use immutable data structures since they're
// easier to reason about and React works very well with them. That's why
// we use map() and filter() everywhere instead of mutating the array or
// "todo" items themselves.
this.todos = this.todos.map(function (todo) {
return Utils.extend({}, todo, { completed: checked })
})
this.inform()
}
app.TodoModel.prototype.toggle = function (todoToToggle) {
this.todos = this.todos.map(function (todo) {
return todo !== todoToToggle
? todo
: Utils.extend({}, todo, { completed: !todo.completed })
})
this.inform()
}
app.TodoModel.prototype.destroy = function (todo) {
this.todos = this.todos.filter(function (candidate) {
return candidate !== todo
})
this.inform()
}
app.TodoModel.prototype.save = function (todoToSave, text) {
this.todos = this.todos.map(function (todo) {
return todo !== todoToSave
? todo
: Utils.extend({}, todo, { title: text })
})
this.inform()
}
app.TodoModel.prototype.clearCompleted = function () {
this.todos = this.todos.filter(function (todo) {
return !todo.completed
})
this.inform()
}
})()