Skip to content

Instantly share code, notes, and snippets.

@tbuschto
Created May 15, 2018 10:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tbuschto/b8cef75deaacdf884441fc387905277f to your computer and use it in GitHub Desktop.
Save tbuschto/b8cef75deaacdf884441fc387905277f to your computer and use it in GitHub Desktop.
decorator factory
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