Skip to content

Instantly share code, notes, and snippets.

@tungd
Last active July 26, 2020 12:09
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tungd/8367229 to your computer and use it in GitHub Desktop.
Save tungd/8367229 to your computer and use it in GitHub Desktop.
/**
* react-catalyst.js
*
* LinkedState for Facebook's React UI Library. Add support for
* deep path state access.
*
* Author: Tung Dao <me@tungdao.com>
*
* Usage:
*
* var WithLink = React.createClass({
* mixins: [ReactCatalyst.LinkedStateMixin],
* getInitialState: function() {
* return { values: [{ text: 'Hello!' }] };
* },
* render: function() {
* return <input type="text" valueLink={this.linkState('values.0.text')} />;
* }
* });
*/
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define([], factory);
} else if (typeof exports === 'object') {
module.exports = factory();
} else {
root.ReactCatalyst = factory();
}
}(this, function () {
"use strict";
function getIn(object, path) {
var stack = path.split('.');
while (stack.length > 1) {
object = object[stack.shift()];
}
return object[stack.shift()];
}
function updateIn(object, path, value) {
var current = object, stack = path.split('.');
while (stack.length > 1) {
current = current[stack.shift()];
}
current[stack.shift()] = value;
return object;
}
function setPartialState(component, path, value) {
component.setState(
updateIn(component.state, path, value));
}
return {
LinkedStateMixin: {
linkState: function(path) {
return {
value: getIn(this.state, path),
requestChange: setPartialState.bind(null, this, path)
}
}
}
}
}));
@gaearon
Copy link

gaearon commented Feb 17, 2014

Sweet.

@tungd
Copy link
Author

tungd commented Apr 21, 2014

I included this here: https://github.com/tungd/react-catalyst, with tests and some other useful mixins.

@tmclnk
Copy link

tmclnk commented May 7, 2014

Hey thanks for this. I've got a bunch of forms I've developing and this scratches an itch for me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment