-
Notifications
You must be signed in to change notification settings - Fork 4
/
Var.js
112 lines (99 loc) · 2.73 KB
/
Var.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
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
App.Var = {
create(name, value) {
const $self = $('<aVar><lockButton/><barsButton/><name>' + name + '</name><input type="text"/><deleteButton/></aVar>');
const $input = $self.children('input');
const $lockButton = $self.children('lockButton');
const $barsButton = $self.children('barsButton');
const $deleteButton = $self.children('deleteButton');
const $name = $self.children('name');
let numDecimalPlaces = 2;
let locked = false;
let hasBar = false;
const self = $self[0];
Object.defineProperties(self, {
value: {
get() {
return value;
},
set(newValue) {
value = newValue;
$input.val(newValue.toFixed(numDecimalPlaces));
$name.attr('title', value);
$self.toggleClass('dirty', false);
}
},
locked: {
get() {
return locked;
},
set(newLocked) {
locked = newLocked;
$self.toggleClass('locked', locked);
}
},
hasBar: {
get() {
return hasBar;
},
set(newHasBar) {
hasBar = newHasBar;
$self.toggleClass('hasBar', hasBar);
}
}
});
self.value = value;
self.name = name;
const ENTER = 13;
const ESC = 27;
$input.keyup(e => {
const dirty = parseFloat($input.val()) !== parseFloat(value.toFixed(numDecimalPlaces));
if (e.keyCode === ENTER && !dirty || e.keyCode === ESC) {
self.value = self.value; // to reset the contents of the input element
$input.blur();
} else {
$self.toggleClass('dirty', dirty);
}
});
$input.change(() => {
if (isAllHashes($input.val())) {
numDecimalPlaces = $input.val().length;
self.value = self.value; // to reset the contents of the input element
$input.blur();
return;
}
const newValue = parseFloat($input.val());
if (Number.isNaN(newValue)) {
return;
}
const oldValue = self.value;
if (newValue !== oldValue) {
self.value = newValue;
$self.trigger('change');
} else {
// Do it anyway just to format the input
self.value = newValue;
}
$input.blur();
});
$lockButton.click(() => {
self.locked = !self.locked;
$self.trigger('lockbuttonclick');
});
$barsButton.click(() => {
self.hasBar = !self.hasBar;
$self.trigger('barsbuttonclick');
});
$deleteButton.click(() => {
$self.trigger('delete');
});
function isAllHashes(str) {
for (let idx = 0; idx < str.length; idx++) {
if (str[idx] !== '#') {
return false;
}
}
return true;
}
return self;
}
};