Completed
Push — master ( 1719ac...509a65 )
by Jeroen De
10s
created

ValidationDispatcher.dispatchIfChanged   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
nc 2
nop 2
dl 0
loc 12
rs 9.4285
c 1
b 0
f 0
1
'use strict';
2
3
/**
4
 *
5
 * @module redux_validation
6
 */
7
8
var _ = require( 'underscore' ),
9
10
	/**
11
	 * The dispatcher checks the form content for fields given in the `fields` property.
12
	 * If they have changed (compared to their equivalent in the `previousFieldValues` property),
13
	 * the `validationFunction` is called with an object with the selected fields.
14
	 * If the validation result is not null, it is sent to the store via the `actionCreationFunction`.
15
	 *
16
	 * @class ValidationDispatcher
17
	 */
18
	ValidationDispatcher = {
19
		validationFunction: null,
20
		actionCreationFunction: null,
21
		fields: null,
22
		previousFieldValues: {},
23
24
		/**
25
		 *
26
		 * @param {Object} formValues
27
		 * @param {Store} store
28
		 * @returns {*} Action object or null
29
		 */
30
		dispatchIfChanged: function ( formValues, store ) {
31
			var selectedValues = _.pick( formValues, this.fields ),
32
				validationResult;
33
34
			if ( _.isEqual( this.previousFieldValues, selectedValues ) ) {
35
				return;
36
			}
37
38
			this.previousFieldValues = selectedValues;
39
			validationResult = this.validationFunction( selectedValues );
40
			return store.dispatch( this.actionCreationFunction( validationResult ) );
41
		}
42
	};
43
44
module.exports = ValidationDispatcher;
45