Passed
Push — master ( e0ac9d...715f03 )
by Paul
04:37
created

GLSR.Ajax.post_   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
/** global: GLSR, jQuery */
2
;(function( $ ) {
3
4
	'use strict';
5
6
	GLSR.Ajax = function( request, ev ) { // object
7
		this.event = ev || null;
8
		this.post = this.post_;
9
		this.request = request;
10
	};
11
12
	GLSR.Ajax.prototype = {
13
		/** @return void */
14
		buildData_: function( el ) { // HTMLElement|null
15
			this.buildNonce_( el );
16
			return {
17
				action: GLSR.action,
18
				ajax_request: true,
19
				request: this.request,
20
			};
21
		},
22
23
		/** @return void */
24
		buildNonce_: function( el ) { // HTMLElement|null
25
			if( this.request.nonce )return;
26
			if( GLSR.nonce[this.request.action] ) {
27
				this.request.nonce = GLSR.nonce[this.request.action];
28
				return;
29
			}
30
			if( !el )return;
31
			this.request.nonce = el.closest( 'form' ).find( '#_wpnonce' ).val();
32
		},
33
34
		/** @return void */
35
		post_: function( callback ) { // function|void
36
			if( this.event ) {
37
				this.postFromEvent_( callback );
38
				return;
39
			}
40
			$.post( GLSR.ajaxurl, this.buildData_(), function( response ) {
41
				if( typeof callback !== 'function' )return;
42
				callback( response );
43
			});
44
		},
45
46
		/** @return void */
47
		postFromEvent_: function( callback ) { // Event, function|void
48
			this.event.preventDefault();
49
			var el = $( this.event.target );
50
			if( el.is( ':disabled' ))return;
51
			el.prop( 'disabled', true );
52
			$.post( GLSR.ajaxurl, this.buildData_( el ), function( response ) {
53
				if( typeof callback === 'function' ) {
54
					callback( response );
55
				}
56
				el.prop( 'disabled', false );
57
			});
58
		},
59
	};
60
})( jQuery );
61