Skip to content

Instantly share code, notes, and snippets.

@thaerlabs
Forked from dsumer/AbstractModel.js
Created December 8, 2017 01:36
Show Gist options
  • Save thaerlabs/42c79558dd883131c50104d9972ab449 to your computer and use it in GitHub Desktop.
Save thaerlabs/42c79558dd883131c50104d9972ab449 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>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment