TypeScriptでAOPを使用する場合は、既存のAOPフレームワークの定義を指定して使用できます。これは、jQuery.aopを使用した完全な例です。
この方法でAOPを使用しても、横断的なコードではAOPコードが表示されないため、既存の定義に影響を与えることはありません。
aop.d.ts
declare class Advice {
unweave(): void;
}
declare interface PointCut {
target: Object;
method: string;
}
declare class Aop {
before: (pointCut: PointCut, advice: Function) => Advice[];
after: (pointCut: PointCut, advice: Function) => Advice[];
afterThrow: (pointCut: PointCut, advice: Function) => Advice[];
afterFinally: (pointCut: PointCut, advice: Function) => Advice[];
around: (pointCut: PointCut, advice: Function) => Advice[];
introduction: (pointCut: PointCut, advice: Function) => Advice[];
}
interface JQueryStatic {
aop: Aop;
}
app.ts
/// <reference path="jquery.d.ts" />
/// <reference path="aop.d.ts" />
class ExampleClass {
exampleMethod() {
alert('Hello');
}
}
jQuery.aop.before(
{ target: ExampleClass, method: 'exampleMethod' },
function () { alert('Before exampleMethod'); }
);
jQuery.aop.after(
{ target: ExampleClass, method: 'exampleMethod' },
function () { alert('After exampleMethod'); }
);
var example = new ExampleClass();
example.exampleMethod();
ソースの例:TypeScriptを使用したAOP。
アップデート
クラスと互換性のあるすべてのクラスに同じ懸念事項を追加するために、基本クラスのポイントを再利用することはできません。これは、ラッパーがポイントでラップされた元の基本クラス関数であり、基本クラスを拡張するクラスの実装が間違っているためです。
これが有効になるのは、関数が呼び出さsuper()
れた場合のみで、その場合はとにかく機能します。
これが私が多くのクラスに同じ懸念を追加する方法です-AopHelperはあなたのプログラムに一度だけ存在する必要があります:
/// <reference path="jquery.d.ts" />
/// <reference path="aop.d.ts" />
class ExampleClass {
exampleMethod() {
alert('Hello');
}
}
class SecondClass extends ExampleClass {
exampleMethod() {
alert('World');
}
}
class AopHelper {
static weave(targets: Object[], method: string, point: Function, advice: Function) {
for (var i = 0; i < targets.length; i++) {
point({ target: targets[i], method: method }, advice );
}
}
}
var classes: any[] = [ExampleClass, SecondClass];
AopHelper.weave(classes, 'exampleMethod', jQuery.aop.before, () => { alert('Before exampleMethod'); });
AopHelper.weave(classes, 'exampleMethod', jQuery.aop.after, () => { alert('After exampleMethod'); });
var example = new SecondClass();
example.exampleMethod();