Last active
May 31, 2016 16:48
-
-
Save bloodbare/90e9e3c3619711908a7193c3a8bedfe6 to your computer and use it in GitHub Desktop.
TypeScript version of adaptation (ZTK)
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
// To run it needs node >= 5 | |
// tsc --experimentalDecorators --target es6 test2.ts | |
// node test2.js | |
let registry = new Map<any, any>(); | |
function implementing(typeInterface: any) { | |
return (target: any) => { | |
if (target.providesInterfaces === undefined) { | |
target.providesInterfaces = [typeInterface]; | |
} else { | |
target.providesInterfaces.push(typeInterface); | |
} | |
return target; | |
} | |
} | |
function adapts(context: any, name: string) { | |
return (target: any) => { | |
if (registry.get(context) === undefined) { | |
registry.set(context, new Map<string, any>()); | |
} | |
if (registry.get(context).get(name) !== undefined) { | |
console.log('Already defined'); | |
} else { | |
registry.get(context).set(name, target); | |
} | |
} | |
} | |
function getAdapter1(context: any, destiny: any, name?: string) { | |
if (name === undefined) { | |
name = ''; | |
} | |
let found = undefined; | |
// we need the class of the | |
for (var index = 0; index < context.constructor.providesInterfaces.length; index++) { | |
if (registry.has(context.constructor.providesInterfaces[index])) { | |
found = registry.get(context.constructor.providesInterfaces[index]) | |
} | |
if (found && found.has(name)) { | |
let factory = found.get(name) | |
return new factory(context) | |
} else { | |
throw "Not found"; | |
} | |
} | |
if (found === undefined) { | |
throw "Not found class" | |
} | |
} | |
interface IBaseContent { | |
} | |
class IBaseContent implements IBaseContent { | |
} | |
interface IView { | |
render(): string | |
} | |
class IView implements IView{ | |
constructor(public context: IBaseContent) { | |
} | |
render() { return ""} | |
} | |
// Page | |
interface IPage { | |
title: string; | |
} | |
class IPage implements IPage { | |
} | |
@implementing(IPage) | |
class Page extends IBaseContent{ | |
constructor(public id: string, public title: string) { | |
super(); | |
} | |
} | |
@implementing(IView) | |
@adapts(IPage, 'view') | |
class PageView implements IView { | |
constructor(public context: Page) { | |
} | |
render() { | |
return "This is the view " + this.context.title; | |
} | |
} | |
let context = new Page("front-page", "Welcome"); | |
let view = getAdapter1(context, IView, 'view') | |
console.log(view.render()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment