Last active
December 8, 2017 01:36
-
-
Save dsumer/56c34cc5e7698d28a00cda4cc80b332f to your computer and use it in GitHub Desktop.
linkState for mobx-state-tree
This file contains hidden or 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
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; |
This file contains hidden or 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
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; |
This file contains hidden or 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
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
Great idea, thanks for sharing 😄