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

+/scripts/admin/ajax.js   B

Complexity

Conditions 1
Paths 2

Size

Total Lines 59

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
nc 2
nop 1
dl 0
loc 59
rs 8.3417
c 1
b 0
f 0

5 Functions

Rating   Name   Duplication   Size   Complexity  
A GLSR.Ajax.postFromEvent_ 0 12 2
A GLSR.Ajax 0 5 1
A GLSR.Ajax.buildNonce_ 0 9 4
A GLSR.Ajax.buildData_ 0 8 1
A GLSR.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( $ ) {
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