Skip to content

Instantly share code, notes, and snippets.

@jo32
Last active February 1, 2016 11:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jo32/977fa29012f2acd3d60a to your computer and use it in GitHub Desktop.
Save jo32/977fa29012f2acd3d60a to your computer and use it in GitHub Desktop.
LinkedStateMixin supporting linked dot expression
/**
* 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