all files / src/ linked-state.js

100% Statements 21/21
100% Branches 14/14
100% Functions 2/2
100% Lines 20/20
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    11× 11×   11×                                                
'use strict';
 
exports.__esModule = true;
exports.createLinkedState = createLinkedState;
 
var _util = require('./util');
 
/** Create an Event handler function that sets a given state property.
 *	@param {Component} component	The component whose state should be updated
 *	@param {string} key				A dot-notated key path to update in the component's state
 *	@param {string} eventPath		A dot-notated key path to the value that should be retrieved from the Event or component
 *	@returns {function} linkedStateHandler
 *	@private
 */
 
function createLinkedState(component, key, eventPath) {
	var path = key.split('.'),
	    p0 = path[0],
	    len = path.length;
	return function (e) {
		var _component$setState;
 
		var t = this,
		    s = component.state,
		    obj = s,
		    v = undefined,
		    i = undefined;
		if (_util.isString(eventPath)) {
			v = _util.delve(e, eventPath);
			if (_util.empty(v) && (t = t._component)) {
				v = _util.delve(t, eventPath);
			}
		} else {
			v = (t.nodeName + t.type).match(/^input(check|rad)/i) ? t.checked : t.value;
		}
		if (_util.isFunction(v)) v = v.call(t);
		if (len > 1) {
			for (i = 0; i < len - 1; i++) {
				obj = obj[path[i]] || (obj[path[i]] = {});
			}
			obj[path[i]] = v;
			v = s[p0];
		}
		component.setState((_component$setState = {}, _component$setState[p0] = v, _component$setState));
	};
}