Skip to content

Instantly share code, notes, and snippets.

@ilopX
Last active November 25, 2019 17:22
Show Gist options
  • Save ilopX/97294cd5d2e9fd5e4479827cc2fb29e0 to your computer and use it in GitHub Desktop.
Save ilopX/97294cd5d2e9fd5e4479827cc2fb29e0 to your computer and use it in GitHub Desktop.
function Event() {
}
const isNode = () => (typeof process !== 'undefined') && (process.release.name === 'node')
Event.check = (func) => {
if (func instanceof Function) {
return func
} else {
throw new Error(`Argument must be a function, current value ${typeof func}`)
}
}
function InputGuardedComponent() {
this.input = isNode()
? {value: ''}
: document.createElement('input')
this._predicate = () => true
this._onChangeEvent = () => {}
}
InputGuardedComponent.prototype.export = function() {
return this.input
}
InputGuardedComponent.prototype.onChange = function(handleChange, predicate = () => true) {
Event.check(handleChange)
Event.check(predicate)
this._onChangeEvent = (val) => {
if (predicate(val)) {
handleChange()
}
}
}
InputGuardedComponent.prototype.setValue = function(value) {
if (this._predicate(value)) {
this.input.value = `${value}`
this._onChangeEvent(value)
}
}
InputGuardedComponent.prototype.setPredicate = function(predicate) {
this._predicate = Event.check(predicate)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment