-
Notifications
You must be signed in to change notification settings - Fork 8
/
payload.js
846 lines (773 loc) · 30.8 KB
/
payload.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
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
/*!
* Payload.js - Javascript Single Page Application Driver
* @see {@link http://payloadjs.com}
*
* @copyright 2015-2017, Philip Klauzinski
* @license Released under the MIT license (http://www.opensource.org/licenses/mit-license.php)
* @author Philip Klauzinski (http://webtopian.com)
* @requires jQuery v1.7+
* @preserve
*/
(function(root, factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// AMD
define(['jquery'], factory);
} else if (typeof exports === 'object') {
// Node
module.exports = factory(require('jquery'));
} else {
// Browser globals
root.Payload = factory(root.jQuery);
}
}(this, function($) {
'use strict';
/**
* Payload.js constructor function
*
* @constructor
*/
var Payload = function() {
var _this = this,
/**
* Will be set to given application DOM context
*
* @private
*/
_$context,
/**
* Default options
*
* @type {{}}
* @private
*/
_options = {
apiAccessToken: '',
apiAfterRender: $.noop,
apiBeforeRender: $.noop,
apiCallback: $.noop,
apiOnClick: function() {
return true;
},
apiOnSubmit: function() {
return true;
},
apiResponseParent: '',
context: 'body',
dataNamespace: '',
debug: false,
loadingDefault: true,
loadingHtml: '<small>Loading...</small>',
partials: (typeof Handlebars === 'undefined') ? {} : Handlebars.partials,
subscribers: [], // [ {events: [], methods: [] } ]
templates: (typeof Handlebars === 'undefined') ? {} : Handlebars.templates,
timeout: 0,
contentType: 'application/json',
xhrAlways: $.noop,
xhrBeforeSend: $.noop,
xhrDone: $.noop,
xhrFail: $.noop
},
_dataPrefix = 'data-' + (_options.dataNamespace ? $.trim(_options.dataNamespace) + '-' : ''),
_selectors = {
API_FORM: 'form[' + _dataPrefix + 'selector],form[' + _dataPrefix + 'url]',
API_LINK: 'a[' + _dataPrefix + 'selector],a[' + _dataPrefix + 'url],button[' + _dataPrefix + 'selector],button[' + _dataPrefix + 'url]',
AUTO_LOAD: '[' + _dataPrefix + 'auto-load]',
CLICK: '[' + _dataPrefix + 'click]',
LOADING: '[' + _dataPrefix + 'role="loading"]'
},
_cache = {
response: {}
},
_payloadEvents = [
'init',
'apiBeforeRender',
'apiAfterRender',
'xhrAlways',
'xhrBeforeSend',
'xhrDone',
'xhrFail'
],
_$payloadEvents = $({}),
_$userEvents = $({}),
/**
* Stores registered Payload components
* If a component is unregistered, it will be removed from this object
*
* @type {{}}
* @private
*/
_components = {},
/**
* Safe console debug
* http://webtopian.com/safe-firebug-console-in-javascript
*
* @param m
* @private
*/
_debug = function(m) {
var args, sMethod;
if (_options.debug && typeof console === 'object' && (typeof m === 'object' || typeof console[m] === 'function')) {
if (typeof m === 'object') {
for (sMethod in m) {
if (m.hasOwnProperty(sMethod)) {
if (typeof console[sMethod] === 'function') {
args = (typeof m[sMethod] === 'string' || (typeof m[sMethod] === 'object' && m[sMethod].length === undefined)) ? [m[sMethod]] : m[sMethod];
console[sMethod].apply(console, args);
} else {
console.log(m[sMethod]);
}
}
}
} else {
console[m].apply(console, Array.prototype.slice.call(arguments, 1));
}
}
},
/**
* Throw Payload.js specific error
*
* @param text
* @private
*/
_error = function(text) {
throw 'Payload.js: ' + text;
},
/**
* Publish Payload internal event
*
* @private
*/
_pub = function() {
_$payloadEvents.trigger.apply(_$payloadEvents, arguments);
},
/**
* Subscribe to Payload internal event
*
* @private
*/
_sub = function() {
_$payloadEvents.on.apply(_$payloadEvents, arguments);
},
/**
* Unsubscribe from Payload internal event
*
* @private
*/
_unsub = function() {
_$payloadEvents.off.apply(_$payloadEvents, arguments);
},
/**
* Test if browser storage API is both supported and available
*
* @param type
* @returns {boolean}
* @private
*/
_storageAvailable = function(type) {
try {
var storage = window[type],
name = '__storage_test__';
storage.setItem(name, 1);
storage.removeItem(name);
return true;
} catch (e) {
return false;
}
},
/**
* Internal JSON API for localStorage
*
* @type {{}}
* @private
*/
_storage = {
/**
* Safely store obj to localStorage or sessionStorage under specified id
* Defaults to localStorage. Pass optional _type param as 'session' to access sessionStorage.
*
* @param id
* @param obj
* @param _type
*/
set: function(id, obj, _type) {
var type = _type === 'session' ? 'sessionStorage' : 'localStorage';
if (_storageAvailable(type)) {
window[type].setItem(id, JSON.stringify(obj));
} else {
_this.debug('warn', type + ' not available');
}
return obj;
},
/**
* Safely get object in localStorage or sessionStorage under specified id
* Defaults to localStorage. Pass optional _type param as 'session' to access sessionStorage.
*
* @param id
* @param _type
*/
get: function(id, _type) {
var type = _type === 'session' ? 'sessionStorage' : 'localStorage',
storage = {};
if (_storageAvailable(type)) {
storage = JSON.parse(window[type].getItem(id));
} else {
_this.debug('warn', type + ' not available');
}
// storage could be null, so return {} if so
return storage || {};
},
/**
* Safely remove localStorage or sessionStorage item under specified id
* Defaults to localStorage. Pass optional _type param as 'session' to access sessionStorage.
*
* @param id
* @param _type
*/
remove: function(id, _type) {
var type = _type === 'session' ? 'sessionStorage' : 'localStorage';
if (_storageAvailable(type)) {
window[type].removeItem(id);
return true;
} else {
_this.debug('warn', type + ' not available');
return false;
}
}
},
/**
* Shortcut methods for accessing _storage API as sessionStorage only
*
* @type {{}}
* @private
*/
_session = {
set: function(id, obj) {
return _storage.set(id, obj, 'session');
},
get: function(id) {
return _storage.get(id, 'session');
},
remove: function(id) {
return _storage.remove(id, 'session');
}
},
// Delegation methods
_delegateApiRequests = function() {
_$context.on('click.api-request auto-load.api-request', _selectors.API_LINK, function(e) {
var $this = $(this);
e.preventDefault();
if ($this.prop('disabled') || $this.hasClass('disabled')) {
return;
}
if (_options.apiOnClick($this, e)) {
_this.apiRequest($this);
}
}).on('submit.api-request auto-load.api-request', _selectors.API_FORM, function(e) {
var $this = $(this);
e.preventDefault();
if (_options.apiOnSubmit($this, e)) {
_this.apiRequest($this);
}
});
},
_delegateClicks = function() {
_$context.on('click.click', _selectors.CLICK, function(e) {
var $this = $(this),
$click = $($this.attr(_dataPrefix + 'click'));
e.preventDefault();
$click.click();
});
},
_initDelegatedBehaviors = function() {
_delegateApiRequests();
_delegateClicks();
},
/**
* Initialization
*
* @returns {Payload}
* @private
*/
_initialize = function() {
_$context = $(_options.context);
if (!_$context.length) {
_error('Selector "' + _options.context + '" not found');
}
_initDelegatedBehaviors();
if (_options.subscribers.length) {
_this.addSubscribers(_options.subscribers);
}
return _this;
},
/**
* Publish the user defined events for a given API request
*
* @param params
* @param namespace
* @private
*/
_publishUserEvents = function(params, namespace) {
var i, event_name;
for (i = 0; i < params.api.events.length; i++) {
event_name = params.api.events[i] + '.' + (namespace || 'afterRender');
_this.publish(event_name, [params]);
}
}
; // End private var declaration
/**
*
* Public vars and methods
*
*/
this.options = _options;
/**
* Stores registered Payload components and gives public access to them, if needed
* Additionally, if a component is unregistered, it will be removed from this object
*
* @type {{}}
*/
this.components = {};
/**
* This object is supplied for storing custom data within your app
* It is exposed within templates via the "app" namespace
*
* @type {{}}
*/
this.appData = {};
/**
* Expose the internal _cache object for external editing
*
* @type {{}}
*/
this.cache = _cache;
/**
* Expose the internal _debug method for external use
*
* @type {_debug}
*/
this.debug = _debug;
/**
* Expose internal storage API
*
* @type {{}}
*/
this.storage = _storage;
/**
* Expose internal storage API with only sessionStorage
*
* @type {{}}
*/
this.session = _session;
/**
* Deliver Payload API functionality to the specified context
*
* @param opts
* @returns {Payload}
*/
this.deliver = function(opts) {
if (typeof(opts) === 'function') {
_options.apiCallback = opts;
} else if (typeof(opts) === 'object') {
_this.merge(opts);
} else if (typeof(opts) === 'string') {
_options.context = opts;
}
return _initialize();
};
/**
* Merge the current options with the given new options
*
* @param opts
* @returns {*}
*/
this.merge = function(opts) {
return $.extend(_options, opts);
};
/**
* Make an API request via the given jQuery $origin object
* This method is called internally when a Payload API object is interacted with in the DOM
* It may also be called directly by supplying any jQuery object with the appropriate attributes
* Optionally pass in data as second parameter to be sent with request
*
* @param $origin
* @param data
* @returns {Payload}
* @todo - break this up into more granular methods
*/
this.apiRequest = function($origin, data) {
var api = {
href: $origin.attr('href'),
url: $origin.attr(_dataPrefix + 'url') || $origin.attr('action'),
method: ($origin.attr(_dataPrefix + 'method') || $origin.attr('method') || 'get').toLowerCase(),
cacheRequest: $origin.attr(_dataPrefix + 'cache-request') || false,
cacheResponse: $origin.attr(_dataPrefix + 'cache-response') || false,
type: $origin.attr(_dataPrefix + 'type') || 'json',
selector: $origin.attr(_dataPrefix + 'selector') || false,
template: _options.templates[$origin.attr(_dataPrefix + 'template')] || false,
partial: _options.partials[$origin.attr(_dataPrefix + 'partial')] || false,
events: $origin.attr(_dataPrefix + 'publish') ? $origin.attr(_dataPrefix + 'publish').split(' ') : [],
requestData: $.extend(
data !== undefined && data.constructor === Array ? [] : {},
_this.serializeObject($origin), data || {},
JSON.parse($origin.attr(_dataPrefix + 'form') || '{}')
),
timeout: $origin.attr(_dataPrefix + 'timeout') || _options.timeout,
templateData: {
app: _this.appData,
view: $origin.data()
},
token: $origin.attr(_dataPrefix + 'token') || _options.apiAccessToken || false,
contentType: $origin.attr(_dataPrefix + 'content-type') || _options.contentType
},
templateName = $origin.attr(_dataPrefix + 'template') || $origin.attr(_dataPrefix + 'partial'),
api_request, $target, $loading, $load, html, templateData, params;
// Add the request payload to the template data under "request" namespace
api.templateData.request = $.extend({
href: api.href,
url: api.url,
method: api.method,
cacheKey: api.url + $origin.serialize()
}, api.requestData);
// Grab a reference to its easier to refer to the cache key
// ... which may be modified by the "pre" events below
api_request = api.templateData.request;
api.loading = ($origin.attr(_dataPrefix + 'loading') ?
JSON.parse($origin.attr(_dataPrefix + 'loading')) : _options.loadingDefault);
// Begin template sequence
if (api.url || api.selector && (api.template || api.partial)) {
$target = $(api.selector);
$loading = $origin.find('[' + _dataPrefix + 'role="loading"]');
params = {
$origin: $origin,
$target: $target,
api: api
};
if (!api.url) {
// User events with "pre" namespace triggered before render
_publishUserEvents(params, 'beforeRender');
_options.apiBeforeRender(params);
_pub('apiBeforeRender', [params]);
html = api.template ? api.template(api.templateData) : api.partial(api.templateData);
$target.html(html);
_options.apiAfterRender(params);
_pub('apiAfterRender', [params]);
}
_options.apiCallback(params);
if (!api.url) {
_publishUserEvents(params);
_this.triggerAutoLoad($target.find(_selectors.AUTO_LOAD));
return _this;
}
if (api.cacheResponse &&
_cache.response[api_request.cacheKey] &&
_cache.response[api_request.cacheKey].data &&
_cache.response[api_request.cacheKey].done
) {
templateData = $.extend({}, _cache.response[api_request.cacheKey].data, api.templateData);
params.response = _cache.response[api_request.cacheKey].response;
// User events with "pre" namespace triggered before render
_publishUserEvents(params, 'beforeRender');
_options.apiBeforeRender(params);
_pub('apiBeforeRender', [params]);
html = api.template ? api.template(templateData) : api.partial(templateData);
$target.html(html);
_options.apiAfterRender(params);
_pub('apiAfterRender', [params]);
_cache.response[api_request.cacheKey].done();
_publishUserEvents(params);
_this.triggerAutoLoad($target.find(_selectors.AUTO_LOAD));
return _this;
}
// Begin AJAX sequence
// Set selector as busy, and show loading indicator if available
$target.attr('aria-busy', true);
if (api.loading) {
$load = $(_options.loadingHtml).attr(_dataPrefix + 'role', 'loading');
$target.empty().prepend($load);
} else if ($loading.length) {
$loading.show();
}
$.ajax({
url: api.url,
type: api.method,
dataType: api.type,
data: (api.method === 'get') ? $.param(data || {}) : JSON.stringify(api.requestData),
contentType: api.contentType,
cache: api.cacheRequest,
timeout: api.timeout,
beforeSend: function(jqXHR, settings) {
var params = {
jqXHR: jqXHR,
settings: settings,
$origin: $origin,
$target: $target,
api: api
};
if (api.token) {
jqXHR.setRequestHeader('Authorization', api.token);
}
_options.xhrBeforeSend(params);
_pub('xhrBeforeSend', [params]);
}
}).done(function(response, status, jqXHR) {
var responseData = _options.apiResponseParent ? response[_options.apiResponseParent] : response,
templateData = $.extend({}, api.templateData, $.isArray(responseData) ? {data: responseData} : responseData),
params = {
response: response,
status: status,
jqXHR: jqXHR,
$origin: $origin,
$target: $target,
html: undefined, // filled in below after HTML is rendered
api: $.extend(api, {templateData: templateData})
},
xhrDone = function() {
_options.xhrDone(params);
_pub('xhrDone', [params]);
_this.triggerAutoLoad($target.find(_selectors.AUTO_LOAD));
},
$loading = $target.find(_selectors.LOADING);
// User events with "pre" namespace triggered before render
_publishUserEvents(params, 'beforeRender');
if ($target.length && api.loading && $loading.length) {
$loading.fadeOut(100, function() {
_options.apiBeforeRender(params);
_pub('apiBeforeRender', [params]);
html = templateName ? (api.template ? api.template(templateData) : api.partial(templateData)) : false;
params.html = html;
$target.html(html);
_options.apiAfterRender(params);
_pub('apiAfterRender', [params]);
xhrDone();
_publishUserEvents(params);
});
} else {
if ($target.length) {
_options.apiBeforeRender(params);
_pub('apiBeforeRender', [params]);
html = templateName ? (api.template ? api.template(templateData) : api.partial(templateData)) : false;
params.html = html;
$target.html(html);
_options.apiAfterRender(params);
_pub('apiAfterRender', [params]);
}
xhrDone();
_publishUserEvents(params);
}
if (api.cacheResponse) {
_cache.response[api_request.cacheKey] = {
response: response,
data: templateData,
done: xhrDone
};
}
}).fail(function(jqXHR, status, error) {
var params = {
jqXHR: jqXHR,
status: status,
error: error,
$origin: $origin,
$target: $target,
api: api
};
_options.xhrFail(params);
_pub('xhrFail', [params]);
}).always(function(responseORjqXHR, status, jqXHRorError) {
var success = (status === 'success'),
params = {
response: success ? responseORjqXHR : null,
jqXHR: (status === 'success') ? jqXHRorError : responseORjqXHR,
status: status,
error: success ? null : jqXHRorError,
$origin: $origin,
$target: $target,
api: api
};
_options.xhrAlways(params);
_pub('xhrAlways', [params]);
// Remove selector busy status
$target.removeAttr('aria-busy');
});
}
return _this;
};
/**
* Trigger the 'auto-load' event on given jQuery object
* When no argument is passed, trigger 'auto-load' if found within the app context
*
* @param $e
* @returns {Payload}
*/
this.triggerAutoLoad = function($e) {
if ($e !== undefined) {
if ($e instanceof $ && $e.length) {
$e.each(function() {
_this.apiRequest($(this));
});
}
} else {
_$context.find(_selectors.AUTO_LOAD).each(function() {
_this.apiRequest($(this));
});
}
return _this;
};
/**
* Publish a custom event
* based on https://github.com/cowboy/jquery-tiny-pubsub
*
* @returns {Payload}
*/
this.publish = function() {
if (arguments[0].indexOf('.') === -1) {
arguments[0] += '.afterRender';
}
_debug('info', '"' + arguments[0] + '"', 'event published.');
_$userEvents.trigger.apply(_$userEvents, arguments);
return _this;
};
/**
* Subscribe to a custom event
* based on https://github.com/cowboy/jquery-tiny-pubsub
*
* @returns {Payload}
*/
this.subscribe = function() {
var namespaceIndex = arguments[0].indexOf('.');
if (namespaceIndex === -1) {
arguments[0] += '.afterRender';
} else if (arguments[0].substr(namespaceIndex) === '.pre') {
// @todo: remove the check for 'pre' namespace in v1.0
arguments[0] = arguments[0].replace('.pre', '.beforeRender');
_debug('warn', 'ATTENTION: The user event \'pre\' namespace has been deprecated. Use \'beforeRender\' instead.');
}
_$userEvents.on.apply(_$userEvents, arguments);
return _this;
};
/**
* Unsubscribe from a custom event
* based on https://github.com/cowboy/jquery-tiny-pubsub
*
* @returns {Payload}
*/
this.unsubscribe = function() {
_$userEvents.off.apply(_$userEvents, arguments);
return _this;
};
/**
* Subscribe custom events to given methods in array of {events: [], methods: []} objects
*
* @param subscribers
* @returns {Payload}
*/
this.addSubscribers = function(subscribers) {
$.each(subscribers, function(i, val) {
if (val.events) {
if (typeof val.events === 'string') {
val.events = [val.events];
}
} else {
return;
}
if (val.methods) {
if (typeof val.methods === 'function') {
val.methods = [val.methods];
}
} else {
return;
}
$.each(val.events, function(j, ev) {
$.each(val.methods, function(k, func) {
_this.subscribe(ev, func);
});
});
});
return _this;
};
/**
* Convert given form input data to an object
*
* @param $form
* @returns {{}}
*/
this.serializeObject = function($form) {
var o = {},
a = $form.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
/**
* Clear cache of specified type ('response' or 'view') and optionally a single key
* To clear all cache, pass no parameters
*
* @param type
* @param key
* @returns {Payload}
*/
this.clearCache = function(type, key) {
if (type === undefined) {
_cache = {
response: {}
};
} else if (type === 'response') {
if (key === undefined) {
_cache.response = {};
} else {
delete _cache.response[key];
}
} else {
return _error('clearCache() - Incorrect type defined');
}
return _this;
};
/**
* Register a component by supplying the name (str) and options (obj)
*
* @param name
* @param options
* @returns {Payload}
*/
this.registerComponent = function(name, options) {
var i;
if (_components[name] !== undefined) {
return _error('registerComponent() - "' + name + '" component already exists');
}
if (options === undefined) {
return _error('registerComponent() - "' + name + '" component options not defined');
}
_components[name] = options;
for (i = 0; i < _payloadEvents.length; i++) {
if (options[_payloadEvents[i]]) {
_sub(_payloadEvents[i] + '.' + name, options[_payloadEvents[i]]);
}
}
_pub('init.' + name);
return _this;
};
/**
* Unregister a previously registered component by supplying the name (str)
*
* @param name
* @returns {Payload}
*/
this.unregisterComponent = function(name) {
if (_components[name] === undefined) {
return _error('unregisterComponent() - "' + name + '" component does not exist');
}
_unsub('.' + name);
delete _components[name];
return _this;
};
};
return new Payload();
}));