-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathajaxnavigator.js
More file actions
82 lines (70 loc) · 2.69 KB
/
ajaxnavigator.js
File metadata and controls
82 lines (70 loc) · 2.69 KB
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
(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__indexOf = Array.prototype.indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
window.AjaxNavigator = (function() {
function AjaxNavigator(replacementSelectors) {
this.replacementSelectors = replacementSelectors;
this.navigateCallback = __bind(this.navigateCallback, this);
this.popstateHandler = __bind(this.popstateHandler, this);
this.clickHandler = __bind(this.clickHandler, this);
this.registerEventHandlers = __bind(this.registerEventHandlers, this);
this.navigate = __bind(this.navigate, this);
this.popped = (function() {
try {
return __indexOf.call(window.history, 'state') >= 0;
} catch (e) {
return false;
}
})();
this.initialURL = location.href;
this.registerEventHandlers();
}
AjaxNavigator.prototype.navigate = function(url) {
($(this)).trigger('unload');
$.get(url, this.navigateCallback);
return $.each(this.replacementSelectors, function(i, sel) {
return ($(sel)).fadeOut(100);
});
};
AjaxNavigator.prototype.registerEventHandlers = function() {
($(window)).on('popstate', this.popstateHandler);
return ($(document)).on('click', 'a[href^="/"]', this.clickHandler);
};
AjaxNavigator.prototype.clickHandler = function(e) {
var url;
url = e.target.href;
history.pushState({
url: url
}, '', url);
this.navigate(url);
return e.preventDefault();
};
AjaxNavigator.prototype.popstateHandler = function(e) {
if (!this.popped && location.href === this.initialURL) return;
this.popped = true;
return this.navigate(e.originalEvent.state.url || location.href);
};
AjaxNavigator.prototype.navigateCallback = function(res) {
this.replaceTitle(res);
this.replaceContent($(res));
return ($(this)).trigger('load');
};
AjaxNavigator.prototype.replaceTitle = function(res) {
var _ref;
return document.title = (_ref = (res.match(/<title>(.*?)<\/title>/))[1]) != null ? _ref : document.title;
};
AjaxNavigator.prototype.replaceContent = function(res) {
var sel, _i, _len, _ref, _results;
_ref = this.replacementSelectors;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
sel = _ref[_i];
_results.push((function(sel) {
return ($(sel)).html(res.find(sel).children()).fadeIn(100);
})(sel));
}
return _results;
};
return AjaxNavigator;
})();
}).call(this);