Created
May 15, 2018 10:23
-
-
Save tbuschto/b8cef75deaacdf884441fc387905277f to your computer and use it in GitHub Desktop.
decorator factory
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 { ui } from 'tabris'; | |
function pattern(regEx: RegExp) { | |
return (prototype: object, property: string) => { | |
const sym = Symbol(); | |
Object.defineProperty(prototype, property, { | |
enumerable: true, | |
set(value: string) { | |
if (!regEx.test(value)) { | |
throw new Error(`Invalid ${property} "${value}"`); | |
} | |
this[sym] = value; | |
}, | |
get() { | |
return this[sym]; | |
} | |
}); | |
}; | |
} | |
class Person { | |
@pattern(/^.+@.+\..+$/) | |
public email: string; | |
} | |
const jack = new Person(); | |
try { | |
jack.email = 'jack@mail.domain'; // OK | |
jack.email = 'none'; // Error: Invalid email "none" | |
} catch(ex) { | |
console.error(ex); | |
} finally { | |
ui.contentView.append(<textView>{jack.email}</textView>); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment