/
input.js
84 lines (72 loc) · 1.97 KB
/
input.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
'use strict';
(function(exports) {
var TodoInputManager = function() {
this._input = null; // Will be an element when starting up.
}
TodoInputManager.prototype = {
drawInput(motd) {
var input = this._input;
input.placeholder = motd.message;
},
fetchData(afterFetch) {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://127.0.0.1:8000/demo-input-motd.json', true);
xhr.responseType = 'json';
xhr.onreadystatechange = function(e) {
// Watch out: we have a mysterious unknown 'this'.
if (this.readyState == 4 && this.status == 200) {
var motd = this.response;
// The flow ends here.
afterFetch(motd);
} else {
// We omit the error in this novice's example.
}
};
xhr.send();
},
saveData(todoItem, afterSave) {
console.log('saved');
afterSave();
},
/**
* After user enter the new item, remove the disabled status.
*/
tidyUp() {
this._input.value = '';
this._input.disabled = false;
},
onUserCreateNewTodo(event, afterCreation) {
var input = this._input;
if (0x0D === event.keyCode) {
var data = {
checked: false,
description: input.value
};
// To prevent user saving multiple times.
input.disabled = true;
this.saveData(data, afterCreation);
// To save this in local, and notify the proxy to sync
// it with the server.
window.dispatchEvent(new CustomEvent('todo-item-created',
{ detail: data }));
}
},
handleEvent(event) {
switch(event.type) {
case 'keydown':
if (event.target === this._input) {
this.onUserCreateNewTodo(event, this.tidyUp.bind(this));
}
break;
}
},
start() {
this._input = document.querySelector('#todo-input');
window.addEventListener('keydown', this);
this.fetchData((function(response) {
this.drawInput(response);
}).bind(this));
}
};
exports.TodoInputManager = TodoInputManager;
})(window);