Skip to content

Instantly share code, notes, and snippets.

@spyl94
Created November 9, 2015 13:11
Show Gist options
  • Save spyl94/440c54d111a0b816b630 to your computer and use it in GitHub Desktop.
Save spyl94/440c54d111a0b816b630 to your computer and use it in GitHub Desktop.
LinkedState decorator example (nécessite babel-polyfill)
import mixin from './mixin';
export default mixin({
linkState(field) {
return {
value: this.state[field],
requestChange: (value) => {
this.setState({[field]: value})
},
};
}
});
import AuthService from './AuthService';
import LinkedState from './LinkedState';
@LinkedState
export default class Login extends React.Component {
constructor(props) {
super(props);
this.state = {
username: '',
password: '',
};
}
login() {
AuthService.login(this.state.username, this.state.password);
}
render() {
return (
<form onSubmit={() => this.login()}>
<div className="form-group">
<input type="text" valueLink={this.linkState('username')} placeholder="Pseudo" />
</div>
<div className="form-group">
<input type="password" valueLink={this.linkState('password')} placeholder="Mot de passe" />
</div>
<div className="form-group">
<button type="submit">Connexion</button>
</div>
</form>
);
}
};
export default function (behaviour, sharedBehaviour = {}) {
const instanceKeys = Reflect.ownKeys(behaviour);
const sharedKeys = Reflect.ownKeys(sharedBehaviour);
const typeTag = Symbol('isa');
function _mixin (clazz) {
for (let property of instanceKeys)
Object.defineProperty(clazz.prototype, property, {
value: behaviour[property],
writable: true
});
Object.defineProperty(clazz.prototype, typeTag, { value: true });
return clazz;
}
for (let property of sharedKeys)
Object.defineProperty(_mixin, property, {
value: sharedBehaviour[property],
enumerable: sharedBehaviour.propertyIsEnumerable(property)
});
Object.defineProperty(_mixin, Symbol.hasInstance, {
value: (i) => !!i[typeTag]
});
return _mixin;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment