Created
November 9, 2015 13:11
-
-
Save spyl94/440c54d111a0b816b630 to your computer and use it in GitHub Desktop.
LinkedState decorator example (nécessite babel-polyfill)
This file contains 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 mixin from './mixin'; | |
export default mixin({ | |
linkState(field) { | |
return { | |
value: this.state[field], | |
requestChange: (value) => { | |
this.setState({[field]: value}) | |
}, | |
}; | |
} | |
}); |
This file contains 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 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> | |
); | |
} | |
}; |
This file contains 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
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