forked from ajp-io/serverless-guestbook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
guestbook.js
79 lines (71 loc) · 1.77 KB
/
guestbook.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
/**
* Web application
*/
const apiUrl = 'https://2323484a.us-south.apigw.appdomain.cloud/guestbook';
const guestbook = {
// retrieve the existing guestbook entries
get() {
return $.ajax({
type: 'GET',
url: `${apiUrl}/entries`,
dataType: 'json'
});
},
// add a single guestbood entry
add(name, email, comment) {
console.log('Sending', name, email, comment)
return $.ajax({
type: 'PUT',
url: `${apiUrl}/entries`,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
name,
email,
comment,
}),
dataType: 'json',
});
}
};
(function() {
let entriesTemplate;
function prepareTemplates() {
entriesTemplate = Handlebars.compile($('#entries-template').html());
}
// retrieve entries and update the UI
function loadEntries() {
console.log('Loading entries...');
$('#entries').html('Loading entries...');
guestbook.get().done(function(result) {
if (!result.entries) {
return;
}
const context = {
entries: result.entries
}
$('#entries').html(entriesTemplate(context));
}).error(function(error) {
$('#entries').html('No entries');
console.log(error);
});
}
// intercept the click on the submit button, add the guestbook entry and
// reload entries on success
$(document).on('submit', '#addEntry', function(e) {
e.preventDefault();
guestbook.add(
$('#name').val().trim(),
$('#email').val().trim(),
$('#comment').val().trim()
).done(function(result) {
// reload entries
loadEntries();
}).error(function(error) {
console.log(error);
});
});
$(document).ready(function() {
prepareTemplates();
loadEntries();
});
})();