Skip to content

Instantly share code, notes, and snippets.

@ArtemAvramenko
Last active August 29, 2015 14:22
Show Gist options
  • Save ArtemAvramenko/bf2d3e649019714e547d to your computer and use it in GitHub Desktop.
Save ArtemAvramenko/bf2d3e649019714e547d to your computer and use it in GitHub Desktop.
// Type definitions for React:
// https://raw.githubusercontent.com/borisyankov/DefinitelyTyped/master/react/react-global.d.ts
declare var __extends: (derived: Object, base: Object) => void;
declare var JSXTransformer: { transform: (jsx: string, opts: Object) => { code: string } };
class ReactUtils {
private static _extends: typeof __extends;
private static _compiled = <{ [key: string]: () => React.ReactElement<any> }>{};
static suppressExtending() {
ReactUtils._extends = __extends;
__extends = () => { };
}
static restoreExtending() {
__extends = ReactUtils._extends;
}
static compileJSX(url: string): () => React.ReactElement<any> {
var func = ReactUtils._compiled[url];
if (func) {
return func;
}
var isFunction: boolean;
var code: string;
$.ajax(url, { async: false, cache: false, dataType: 'text' }).then((jsx: string) => {
isFunction = !jsx.indexOf('()');
code = JSXTransformer.transform(jsx, {
harmony: true,
target: 'es5'
}).code;
});
if (isFunction) {
code = code.substring(code.indexOf('{') + 1, code.lastIndexOf('}'));
} else {
code = 'return ' + code;
}
func = <() => any>new Function('', code);
ReactUtils._compiled[url] = func;
return func;
}
static createComponentClass<P, S>(spec: React.ComponentSpec<P, S>): React.ClassicComponentClass<P> {
var mixin = <React.ComponentSpec<P, S>>{};
for (var i in spec) {
mixin[i] = spec[i];
}
var proto = (<Function><any>spec).prototype;
for (i in proto) {
mixin[i] = proto[i];
}
return React.createClass(mixin);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment