Revision 5fad86446386 () - Diff

Link to this snippet: https://friendpaste.com/ZGASyFWVMIuvFlCYDkjfL
Embed:
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
111
112
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-type" content="application/xhtml+xml; charset=utf-8"/>
<title>My Todos</title>
<script src="../script/couch.js" type="text/javascript" charset="utf-8"></script>
<script src="../script/json.js" type="text/javascript" charset="utf-8"></script>

<script type="text/javascript" charset="utf-8">
function $(e)
{
return document.getElementById(e);
}

var Couch_Todo =
{
_todos:{},
db: new CouchDB("todo"),

insert: function(todo)
{
// DOM-fu
var list_item = document.createElement("li");
list_item.innerHTML = todo.text + ' <a href="#" onClick="Couch_Todo.remove(this.parentNode); return false;">X</a>';

$("todos").insertBefore(list_item, $("todos").firstChild);

this._todos[todo._id] = todo; // save todo object, so we can access the _rev when we want to delete.
list_item.id = todo._id; // save new id in DOM object

this.updateEmpty();
},

add: function(todo)
{
//automatically save time
todo.time = (new Date()).getTime();
this.db.save(todo);
this.insert(todo);
},

load:function()
{
var all_docs = this.db.view("todo/all");

if(all_docs && all_docs.total_rows > 0) {
for(var idx = 0; idx < all_docs.total_rows; idx++) {
var todo = all_docs.rows[idx];
this.insert({
_id:todo.id,
_rev:todo.value.rev,
text:todo.value.text
});
}
}
},

remove:function(li)
{
var doc = this._todos[li.id];
this.db.deleteDoc(doc);
this._todos[li.id] = null;

$("todos").removeChild($(li.id));
this.updateEmpty();

// focus the input field
$("todo").focus();
},

updateEmpty: function()
{
//if there are no todos, show a message
$("empty").style.display = (0 == $("todos").childNodes.length)?"block":"none";
}
}

window.onload = function()
{
// load saved todos
Couch_Todo.load();

// what to do when hitting enter in the input field
$("add").onsubmit = function()
{
var value = $("todo").value;
$("todo").value = ""; // reset input box
if(value) { // don't add empty todos
Couch_Todo.add({text:value});
}

// don't submit the form
return false;
}

// focus the input field when the document loads
$("todo").focus();
}
</script>
</head>

<body id="index">
<form id="add" action="">
<input type="text" name="todo" value="" id="todo"/>
</form>

<ul id="todos"></ul>

<div id="empty">Enter todo items in the box above and hit enter.</div>
</body>
</html>