01.
$(
function
() {
03.
todoItemTable = client.getTable(
'todoitem'
);
04.
05.
06.
07.
function
refreshTodoItems() {
08.
var
query = todoItemTable.where({ complete:
false
});
09.
10.
query.read().then(
function
(todoItems) {
11.
var
listItems = $.map(todoItems,
function
(item) {
12.
return
$(
'<li>'
)
13.
.attr(
'data-todoitem-id'
, item.id)
14.
.append($(
'<button class="item-delete">Delete</button>'
))
15.
.append($(
'<input type="checkbox" class="item-complete">'
).prop(
'checked'
, item.complete))
16.
.append($(
'<div>'
).append($(
'<input class="item-text">'
).val(item.text)));
17.
});
18.
19.
$(
'#todo-items'
).empty().append(listItems).toggle(listItems.length > 0);
20.
$(
'#summary'
).html(
'<strong>'
+ todoItems.length +
'</strong> item(s)'
);
21.
}, handleError);
22.
}
23.
24.
function
handleError(error) {
25.
var
text = error + (error.request ?
' - '
+ error.request.status :
''
);
26.
$(
'#errorlog'
).append($(
'<li>'
).text(text));
27.
}
28.
29.
function
getTodoItemId(formElement) {
30.
return
Number($(formElement).closest(
'li'
).attr(
'data-todoitem-id'
));
31.
}
32.
33.
34.
$(
'#add-item'
).submit(
function
(evt) {
35.
var
textbox = $(
'#new-item-text'
),
36.
itemText = textbox.val();
37.
if
(itemText !==
''
) {
38.
todoItemTable.insert({ text: itemText, complete:
false
}).then(refreshTodoItems, handleError);
39.
}
40.
textbox.val(
''
).focus();
41.
evt.preventDefault();
42.
});
43.
44.
45.
$(document.body).on(
'change'
,
'.item-text'
,
function
() {
46.
var
newText = $(
this
).val();
47.
todoItemTable.update({ id: getTodoItemId(
this
), text: newText }).then(
null
, handleError);
48.
});
49.
50.
$(document.body).on(
'change'
,
'.item-complete'
,
function
() {
51.
var
isComplete = $(
this
).prop(
'checked'
);
52.
todoItemTable.update({ id: getTodoItemId(
this
), complete: isComplete }).then(refreshTodoItems, handleError);
53.
});
54.
55.
56.
$(document.body).on(
'click'
,
'.item-delete'
,
function
() {
57.
todoItemTable.del({ id: getTodoItemId(
this
) }).then(refreshTodoItems, handleError);
58.
});
59.
60.
61.
refreshTodoItems();
62.
});