This project is read-only.

Elsewhere

http://www.stevefenton.co.uk/Content/Blog/Date/201212/Blog/AOP-In-TypeScript-Using-Aspect/

Getting Started

You just need to include Aspect.ts in your TypeScript program.

Adding Cross-Cutting Concerns

All of the function in Aspect have the same signature, whether you are adding your cross cutting concerns before a method call, after one or when there is an error.

You pass in three arguments...

    aspectWeaver.before( [ClassName], [FunctionName], [Handler]);
  • ClassName is the direct reference to the TypeScript class, i.e. CalculationModule.BalanceSheet
  • FunctionName is the name of the function as a string, i.e. 'getBalanceSheetData`
  • Handler is the function to execute (in this case before the original function call)

Aspect ensures that the original code is unaffected by calling the original function and returning its return value to the original caller.

Here is an example:

/// <reference path="YourModuleName.ts" />
/// <reference path="Aspect.ts" />

var aspectWeaver = new Aspect.Weaver();

aspectWeaver.before(
    YourModuleName.YourClassName,
    'yourMethodName',
    (event: Aspect.WeaveEvent, args) => {
        alert(event.toString());
    }
);

aspectWeaver.error(
    YourModuleName.YourClassName,
    'yourMethodName',
    (event: Aspect.WeaveEvent, args) => {
        console.log(event.toString());
    }
);

Handlers

Your handler will be passed two arguments.
  • event - A WeaveEvent class containing the event type, method it is linked to and any error
  • args - the arguments passed to the linked method

Here are some examples of how you might use AOP with Aspect.

Rather than adding logging code to all of your classes, you could have a Logging.ts file that uses Aspect to attach logging using the error event. You could even have a diagnostic switch that logged all calls to methods using the before event. Your logger has access to the method names and all of the arguments that are passed.

Rather than have extensive parameter validation inside of a method, you could use Aspect to check parameters before a method is called using the before event. This moves the validation concern out of the method, so the method can have a single clear purpose. You have access to all of the arguments so you can check they are valid.

Last edited Nov 8, 2012 at 5:17 PM by Sohnee, version 3

Comments

No comments yet.