Last active
February 1, 2016 11:27
-
-
Save jo32/977fa29012f2acd3d60a to your computer and use it in GitHub Desktop.
LinkedStateMixin supporting linked dot expression
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* not offical link state mixin, created by jolamjiang, 20160201184405 | |
* Usage: | |
* <input type="text" className="form-control" id="rule-name" valueLink={this.linkState('rule.rule_name')} /> | |
*/ | |
'use strict'; | |
var ReactLink = require('react/lib/ReactLink'); | |
function getKeyValueRecursively(obj, key) { | |
if (!obj || !key) { | |
throw new Error('key or obj is not given'); | |
} | |
let keyLink = key.split('.'); | |
let cursor = obj; | |
let tempKey; | |
for (let i = 0; i < keyLink.length; i++) { | |
tempKey = keyLink[i]; | |
cursor = cursor[tempKey]; | |
if (!cursor && i != keyLink.length - 1) { | |
throw new Error('link of object is not complete'); | |
} | |
} | |
return cursor; | |
} | |
function setKeyValueRecursively(obj, key, value) { | |
if (!obj || !key || !value) { | |
throw new Error('key or obj is not given'); | |
} | |
let keyLink = key.split('.'); | |
let cursor = obj; | |
let tempKey; | |
for (let i = 0; i < keyLink.length - 1; i++) { | |
tempKey = keyLink[i]; | |
cursor = cursor[tempKey]; | |
if (!cursor && i != keyLink.length - 2) { | |
throw new Error('link of object is not complete'); | |
} | |
} | |
cursor[keyLink[keyLink.length - 1]] = value; | |
} | |
var RecursiveLinkedStateMixin = { | |
linkState: function(key) { | |
return new ReactLink( | |
getKeyValueRecursively(this.state, key), | |
(function(value) { | |
setKeyValueRecursively(Object.assign({}, this.state), key, value); | |
this.setState(this.state); | |
}).bind(this) | |
); | |
} | |
}; | |
module.exports = RecursiveLinkedStateMixin; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment