Last active
November 25, 2019 17:22
-
-
Save ilopX/97294cd5d2e9fd5e4479827cc2fb29e0 to your computer and use it in GitHub Desktop.
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
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