Created
June 23, 2018 17:00
-
-
Save kareniel/65acbd501f19fb7263459cb2691a32c4 to your computer and use it in GitHub Desktop.
Reactivity in Choo
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
var Component = require('choo/component') | |
const NO_COMPONENT = 'Model constructor expects a Component as first argument.' | |
module.exports = class Model { | |
constructor (component, opts) { | |
if (!component || !(component instanceof Component)) { | |
throw new Error(NO_COMPONENT) | |
} | |
this.component = component | |
this.opts = opts | |
this.value = '' | |
this.update = this.update.bind(this) | |
} | |
update (e) { | |
this.value = e.target.value | |
this.component.rerender() | |
} | |
reset () { | |
this.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
var Component = require('choo/component') | |
var html = require('choo/html') | |
var Model = require('./Model') | |
module.exports = class SomeComponent extends Component { | |
constructor (name, state, emit) { | |
super() | |
this.fields = { | |
name: new Model(this) | |
} | |
} | |
update () { | |
return false | |
} | |
createElement () { | |
return html` | |
<form> | |
<p> | |
<label>Name</label><br> | |
<input type="text" | |
value=${this.fields.name.value} | |
onkeyup=${this.fields.name.update}> | |
</p> | |
<button onclick=${this.onSubmit}> | |
OK | |
</button> | |
</form>` | |
} | |
clear () { | |
Object.keys(this.fields).forEach(key => { | |
this.fields[key].reset() | |
}) | |
} | |
onSubmit (e) { | |
e.preventDefault() | |
this.clear() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment