Skip to content

Instantly share code, notes, and snippets.

@dsumer
Last active December 8, 2017 01:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dsumer/56c34cc5e7698d28a00cda4cc80b332f to your computer and use it in GitHub Desktop.
Save dsumer/56c34cc5e7698d28a00cda4cc80b332f to your computer and use it in GitHub Desktop.
linkState for mobx-state-tree
import {types, getType} from 'mobx-state-tree';
function getValueFromPath(value, valuePath) {
if (valuePath) {
const path = valuePath.split('.');
let endValue = value;
for (const pathItem of path) {
endValue = endValue[pathItem];
}
return endValue;
} else {
if (value.target && (value.target.checked || value.target.value)) {
if (value.target.checked) {
return value.target.checked;
} else {
return value.target.value;
}
} else {
return value;
}
}
}
const linkCache = {};
const AbstractModel = types.model('AbstractModel').actions((self) => ({
link: function (key, valuePath) {
const modelName = getType(self).name;
let identifier = modelName + self.$treenode.nodeId + key;
if (valuePath) {
identifier += valuePath;
}
if (linkCache[identifier]) {
return linkCache[identifier];
} else {
return (linkCache[identifier] = function (value) {
self[key] = getValueFromPath(value, valuePath);
});
}
}
}));
export default AbstractModel;
import {types} from 'mobx-state-tree';
import AbstractModel from './AbstractModel';
const Car = AbstractModel.named('CarModel').props({
name: types.string,
color: types.string
});
export default Car;
import React from 'react';
import {observer} from 'mobx-react';
@observer
export default class EditCarComponent extends React.Component {
render() {
//car is an instance of CarModel
const {car} = this.props;
return (
<div>
<h1>Edit your Car</h1>
<div>
<label>Abteilung:</label>
<input type="text" value={car.name} onChange={car.link('name')}/>
</div>
<div>
<label>Abteilung:</label>
<input type="text" value={car.color} onChange={car.link('color')}/>
</div>
</div>
);
}
}
@thaerlabs
Copy link

Great idea, thanks for sharing 😄

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