Passed
Push — master ( 06bde6...6d2f62 )
by Paul
04:59
created

+/scripts/admin/ajax.js   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 60

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 60
rs 9.5555
c 1
b 0
f 0

5 Functions

Rating   Name   Duplication   Size   Complexity  
A Ajax.buildData_ 0 7 1
A ajax.js ➔ Ajax 0 5 1
A Ajax.buildNonce_ 0 9 4
A Ajax.postFromEvent_ 0 12 2
A Ajax.post_ 0 10 2

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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