forked from iSimonWeb/jBridge
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjQuery.Bridge.js
More file actions
413 lines (344 loc) · 10.6 KB
/
jQuery.Bridge.js
File metadata and controls
413 lines (344 loc) · 10.6 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
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
/**
* @project: jQuery.Bridge v0.1
* @description: and easy, abstract and versatile AJAX + History API site manager
* @author: Laser Design Studio http://laserdesignstudio.it
*/
(function($) {
var synchronize = function(functions) {
if (functions.length == 1)
return functions[0]();
return synchronize(functions.slice(0, -1)).then(functions.pop());
};
jQuery.Bridge = function(options) {
var bridge = {},
globalDeferred = null,
deferredStackCount = 0;
// Plugin's options obj ============================================================
// =================================================================================
var settings = $.extend({
// @type: CSS selector
// Matches menu(s)' anchors
menuAnchors: 'nav.main a',
// @type: CSS selector / null
// Matches anchor's parent that will get .active class
// leave null if you want that class on anchors
menuAnchorsContainer: null,
// @type: CSS selector
// Matches anchors to be AJAXified
internalAnchors: 'a[href^="/"]',
//
onUnload: bridge.bypass,
//
onPageUnload: {},
//
onLoad: bridge.bypass,
//
onScriptsLoad: function() {},
//
onPageLoad: {},
// Fired every time hashFragment is changed
onHashChange: null,
// Fired on form-submit
onFormSubmit: function() {},
// Hey Bridge, talk to me!
debug: false
}, options);
// Elements cache ==================================================================
// =================================================================================
var $body = $('body');
var $anchors = $(settings.menuAnchors);
// Utility functions ===============================================================
// =================================================================================
/**
* Returns current pathname
*
* @return {string}
*/
bridge.getPathname = function() {
return document.location.pathname.replace(/#.*$/, '');
};
/**
* Logs 'message' if settings.debug is true
*
* @params {mixed} message, something to log
*/
bridge.log = function(message) {
if (settings.debug)
console.log(message);
}
/**
* Replace current pathname and load url
*
* @param {string} url
*/
bridge.goto = function(url) {
history.pushState({'route': url}, '', url);
bridge.load();
};
/**
* Append 'url' to current pathname
*
* @param {string} url
*/
bridge.replaceAppend = function(url) {
history.replaceState(history.state, '', bridge.getPathname() + url);
};
bridge.hold = function(stackCount) {
bridge.log('Bridge is on hold');
if (globalDeferred === null) {
if (stackCount !== undefined)
deferredStackCount = stackCount;
else deferredStackCount++;
globalDeferred = new $.Deferred();
return globalDeferred.promise();
}
};
bridge.release = function() {
if (globalDeferred === null) return;
if (deferredStackCount > 0)
deferredStackCount--;
bridge.log('Stack length -> ' + deferredStackCount);
if (deferredStackCount == 0) {
bridge.log('Bridge released');
globalDeferred.resolve();
globalDeferred = null;
}
};
bridge.getPromise = function() {
if (globalDeferred === null)
return bridge.bypass();
return globalDeferred.promise();
};
/**
* Do nothing, used when bridge can continue executing
*
* @return {$.Promise}
*/
bridge.bypass = function() {return (new $.Deferred()).resolve().promise();};
// Match current page function
var findRelatedFunction = function(obj) {
var f = bridge.bypass(),
pathname = bridge.getPathname();
for (var key in obj)
if (pathname.indexOf(key) == 0)
f = obj[key];
return f;
};
// Event Handlers ==================================================================
// =================================================================================
// AJAXify all internal anchors
$(document).on('click', settings.internalAnchors, function(e) {
e.preventDefault();
var $anchor = $(this),
href = $anchor.attr('href');
// If same path, do nothing
if (href == bridge.getPathname())
return false;
// Log link click
bridge.log('Click on: "' + href + '"');
// Else push anchor href and load page
bridge.goto(href);
});
// Handle hash-change event if handler has been specified
$(document).on('click', 'a[href^=#]', function(e) {
if (settings.onHashChange === null)
return false;
var hashFragment = $(this).attr('href');
//bridge.replaceAppend(hashFragment);
settings.onHashChange(hashFragment);
return false;
});
// TO BE FIXED
// Handle form submit
/*$(document).on('submit', 'form', function(e) {
e.preventDefault();
// Retrieve data
var $this = $(this),
formID = $this.attr('id'),
method = $this.attr('method').toLowerCase(),
url = $this.attr('action'),
data = JSON.stringify($this.serializeObject());
if ($.inArray(method, ['get', 'post', 'put', 'delete']) === -1)
return;
$this.addClass('loading');
$defer = $.ajax({
'url': url,
'type': method,
'data': data,
'context': this
});
settings.onFormSubmit($defer);
});*/
// Handle onpopstate event preventing the first
// and unuseful fire in webkit browsers
var initialLoad = false;
window.onpopstate = function() {
// Check if window.load has been fired once
if (!initialLoad) return false;
bridge.load();
return false;
};
// Wait for window onLoad to init plugin
$(window).one('load', function() {
var currentPath = bridge.getPathname();
var currentPageLoad = findRelatedFunction(settings.onPageLoad);
// Select current menu item
setActiveItem();
// Synchronize plugin operation
synchronize([settings.onLoad, currentPageLoad]);
// Enable onpopstate listener
setTimeout(function() {initialLoad = true;}, 0);
});
// Main functions ==================================================================
// =================================================================================
/**
* Match the current anchor among settings.menuAnchors
* and adds .active class to it or its parent
* based on settings.menuAnchorsContainer
*/
var setActiveItem = function() {
var currentPath = bridge.getPathname(),
$targetAnchors = $anchors;
$anchors.removeClass('active');
if (settings.menuAnchorsContainer === null)
$targetAnchors
.filter(function(index) {
return currentPath.indexOf($(this).attr('href')) != -1;
})
.addClass('active');
else
$targetAnchors
.filter(function(index) {
return currentPath.indexOf($(this).attr('href')) != -1;
})
.parents(settings.menuAnchorsContainer)
.addClass('active');
};
/**
* Make a POST request using window.location
*
* @return {jQuery.Deferred}
*/
bridge.requestPage = function() {
bridge.log('Requesting page: ' + window.location);
return $.post(window.location);
};
/**
* Replace sections received by requestPage
* 'title', 'stylesheets' and 'scripts'
* are treated as special sections
*
* @param {Object} pageSections
* @return {jQuery.Promise}
*/
bridge.replaceContent = function(pageSections) {
// Replace title
var title = $(pageSections['title']).filter('title').text();
$('head > title').text(title);
delete pageSections['title'];
// Append stylesheets
bridge.appendStyles(pageSections['stylesheets']);
delete pageSections['stylesheets'];
// Append scripts
var scriptsPromise = bridge.appendScripts(pageSections['scripts']);
delete pageSections['scripts'];
// Log sections replacement
bridge.log('Replacing section(s)');
// Replace sections
$.each(pageSections, function(name, content) {
$('#' + name).html($.parseHTML(content));
});
if (scriptsPromise)
return scriptsPromise;
else
return bridge.bypass();
};
/**
* Check if styles do not exist in DOM
* and append them if necessary
*
* @param {string} styles
*/
bridge.appendStyles = function(styles) {
var $styles = $(styles);
// If no stylesheets passed, exit
if (!$styles.length) return;
// Log stylesheets discovery
bridge.log($styles.length + ' stylesheet(s) found, checking existance');
$.each($styles, function(index, style) {
var $style = $(style);
var href = $style.attr('href');
var name = href.split('/').slice(-1)[0];
// Check if stylesheet already exist in DOM
if ($('link[href$="' + name + '"]').length)
return;
// Log style's href
bridge.log('Appending stylesheet -> ' + href);
// Otherwise append the stylesheet to head
$('head').append($style);
});
};
/**
* Check if scripts do not exist in DOM
* and append them if necessary.
* Call settings.onScriptsLoad on appended scripts load
*
* @param {string} scripts
* @return {jQuery.Promise}
*/
bridge.appendScripts = function(scripts) {
var $scripts = $($.trim(scripts));
//deferreds = [];
// If no script passed, exit
if (!$scripts.length) return;
// Log script discovery
bridge.log($scripts.length + ' script(s) found, checking existance');
bridge.hold(
$scripts.filter(':not([async])').length +
$scripts.filter('[src*="bridge.release"]').length
);
$.each($scripts, function(index, script) {
var $script = $(script);
var src = $script.attr('src');
var async = $script.is('[async]');
// Check if script already exist in DOM
if ($('script[src="' + src + '"]').length) {
// If there's a callback to bridge.release,
// manually release brige once
if (src.match('bridge.release'))
bridge.release();
return bridge.release();
}
// Log script's src
bridge.log('Appending script -> ' + src);
// Create script element
$script = $('<script />');
$('body').append($script);
$script.one('load', bridge.release);
$script.attr('src', src);
});
// Return a Promise to wait scripts load
return bridge.getPromise();
};
/**
* Synchronize plugin operations
*/
bridge.load = function() {
var currentPath = bridge.getPathname();
var currentPageUnload = findRelatedFunction(settings.onPageUnload);
var currentPageLoad = findRelatedFunction(settings.onPageLoad);
// Select current menu item
setActiveItem();
// Synchronize plugin operation
synchronize([
settings.onUnload,
currentPageUnload,
bridge.requestPage,
bridge.replaceContent,
settings.onLoad,
currentPageLoad
]);
};
return bridge;
};
})(jQuery);