-
Notifications
You must be signed in to change notification settings - Fork 4
/
PageController.js
104 lines (86 loc) · 3 KB
/
PageController.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
define(function(require) {
'use strict';
var $ = require('zepto');
var mediator = require('mediator-js');
var prime = require('prime');
var Spinner = require('modules/Spinner');
var Scroller = require('modules/Scroller');
var PageUpdater = require('modules/PageUpdater');
var storage = require('modules/Storage');
return prime({
constructor: function(elements) {
$.each(elements, function(key, value) {
this[key] = $(value);
}.bind(this));
new Spinner(this.container, {
show: 'content:get:before',
hide: 'content:get:always'
});
new Scroller({
contentLoad: 'content:get:done'
});
new PageUpdater(this.nav, this.injectTarget, {
contentLoad: 'content:get:done'
});
this.attachEvents();
},
attachEvents: function() {
this.container.on('click', this.links.selector, this.getPageContent.bind(this));
window.addEventListener('popstate', function(event) {
// Chrome/Safari seem to fire popstate on normal page load, bah
// http://goo.gl/JJfwR
if (!event.state) {
return;
}
mediator.publish('content:get:done', {
response: event.state,
navType: 'popstate'
});
}.bind(this));
},
getPageContent: function(event) {
var href = (typeof event == 'string' ? event : event.currentTarget.href);
// Try to get the page from storage first
if (!this.fetchFromStorage(href)) {
this.fetchFromServer(href);
}
event && event.preventDefault();
},
fetchFromStorage: function(href) {
var json = storage.getItem(href);
if (!json) {
return null;
}
mediator.publish('content:get:done', {
response: json,
href: href
});
return json;
},
fetchFromServer: function(href) {
var req = $.ajax({
data: { ajax: true },
dataType: 'json',
context: this,
timeout: 6000,
url: href,
beforeSend: function() {
mediator.publish('content:get:before');
}
});
req.always(function() {
mediator.publish('content:get:always');
});
req.fail(function() {
mediator.publish('content:get:fail');
});
req.done(function(json) {
mediator.publish('content:get:done', {
response: json,
href: href
});
storage.setItem(href, json);
});
}
});
});