-
Notifications
You must be signed in to change notification settings - Fork 2
/
command_history.js
63 lines (50 loc) · 1.74 KB
/
command_history.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
define(['jquery'], function ($) {
var CommandHistory = function () {
this.lastCommand = 0;
this.history = [];
var self = this;
// @TODO - add event listener on input element, not on entire window.
// http://stackoverflow.com/questions/1314450/jquery-how-to-capture-the-tab-keypress-within-a-textbox
window.onkeyup = function (e) {
var key = e.keyCode ? e.keyCode : e.which,
upPressed = key == 38,
downPressed = key == 40;
if (upPressed) {
self.lastCommand--;
} else if (downPressed) {
self.lastCommand++;
}
if (upPressed || downPressed) {
self.populateInput();
}
}
};
CommandHistory.prototype = {
init: function (input) {
this.input = input;
},
log: function (command) {
this.history.push(command);
this.lastCommand = this.history.length;
},
clear: function () {
this.history = [];
},
get: function () {
return this.history;
},
populateInput: function () {
if (this.history.length > 0) {
this.validateLastCommandIndex();
this.input.val(this.history[this.lastCommand]);
}
},
validateLastCommandIndex: function () {
var minIndex = 0,
maxIndex = this.history.length - 1;
this.lastCommand = (this.lastCommand > maxIndex) ? maxIndex : this.lastCommand;
this.lastCommand = (this.lastCommand < minIndex) ? minIndex : this.lastCommand;
}
}
return new CommandHistory();
});