Created
January 25, 2014 19:36
-
-
Save NV/8622188 to your computer and use it in GitHub Desktop.
React.js deep linkState http://stackoverflow.com/questions/21057219/react-js-2-way-bindings-two-levels-deep-path-in-valuelink
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
var DeepLinkState = { | |
linkState: function(path) { | |
function setPath(obj, path, value) { | |
var leaf = resolvePath(obj, path); | |
leaf.obj[leaf.name] = value; | |
} | |
function getPath(obj, path) { | |
var leaf = resolvePath(obj, path); | |
return leaf.obj[leaf.name]; | |
} | |
function resolvePath(obj, names) { | |
if (typeof names === 'string') { | |
names = names.split('.'); | |
} | |
var lastIndex = names.length - 1; | |
var current = obj; | |
for (var i = 0; i < lastIndex; i++) { | |
var name = names[i]; | |
current = current[name]; | |
} | |
return { | |
obj: current, | |
name: names[lastIndex] | |
} | |
} | |
return { | |
value: getPath(this.state, path), | |
requestChange: function(newValue) { | |
setPath(this.state, path, newValue); | |
this.forceUpdate(); | |
}.bind(this) | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is better. https://github.com/EarthlingInteractive/react-deep-link-state/blob/master/DeepLinkedStateLib.js