-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathapp.js
105 lines (80 loc) · 2.21 KB
/
app.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
(function(){
var $ = document.getElementById.bind(document);
var $$ = document.querySelectorAll.bind(document);
var App = function($el){
this.$el = $el;
this.load();
this.$el.addEventListener(
'submit', this.submit.bind(this)
);
if (this.dob) {
this.renderAgeLoop();
} else {
this.renderChoose();
}
};
App.fn = App.prototype;
App.fn.load = function(){
var value;
if (value = localStorage.dob) {
this.dob = new Date(parseInt(value));
this.dob.setTime(this.dob.getTime() + 1000 * 60 * this.dob.getTimezoneOffset());
}
};
App.fn.save = function(){
if (this.dob)
localStorage.dob = this.dob.getTime();
};
App.fn.submit = function(e){
e.preventDefault();
var input = this.$$('input')[0];
if ( !input.valueAsDate ) return;
this.dob = input.valueAsDate;
this.save();
this.dob.setTime(this.dob.getTime() + 1000 * 60 * this.dob.getTimezoneOffset());
this.renderAgeLoop();
};
App.fn.renderChoose = function(){
this.html(this.view('dob')());
};
App.fn.renderAgeLoop = function(){
this.interval = setInterval(this.renderAge.bind(this), 100);
};
App.fn.calculateAge = function(){
var now = new Date
var age = now.getFullYear() - this.dob.getFullYear();
var mDiff = now.getMonth() - this.dob.getMonth();
if (mDiff < 0 || (mDiff === 0 && now.getDate() < this.dob.getDate())) {
age--;
}
return age;
};
App.fn.calculateMS = function(){
var now = new Date
var janOne = new Date(now.getFullYear(), 0, 1);
var comingBirthday = new Date(this.dob.getTime());
var ms;
comingBirthday.setYear(now.getFullYear());
ms = (now.getTime() - janOne.getTime()) / (comingBirthday.getTime() - janOne.getTime());
return ms.toFixed(9).toString().split('.')[1];
};
App.fn.renderAge = function(){
requestAnimationFrame(function(){
this.html(this.view('age')({
year: this.calculateAge(),
milliseconds: this.calculateMS()
}));
}.bind(this));
};
App.fn.$$ = function(sel){
return this.$el.querySelectorAll(sel);
};
App.fn.html = function(html){
this.$el.innerHTML = html;
};
App.fn.view = function(name){
var $el = $(name + '-template');
return Handlebars.compile($el.innerHTML);
};
window.app = new App($('app'))
})();