执行底层函数时调用typescript decorator方法

Pra*_*tta 2 typescript typescript1.5

根据打字稿设计的工作原理,如果我写一个装饰师,

class foo{

   @fooDecorator
   public fooMethod(){

    }
}
Run Code Online (Sandbox Code Playgroud)

它将转换后的javascript作为

var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
 };
var foo = (function () {
function foo() {
}
foo.prototype.fooMethod = function () {
};
__decorate([
    fooDecorator
], foo.prototype, "fooMethod", null);
return foo;
}());
Run Code Online (Sandbox Code Playgroud)

每当我的应用程序被引导时,每次我的应用程序都会执行修饰代码函数执行,但我想要的是每当底层函数"fooMethod"被执行时,装饰器方法"fooDecorator"应该执行,我怎样才能达到相同的效果,请帮助我问题

Ami*_*mid 8

你可以这样做.在装饰器中用'wrapper'替换原始方法,首先调用应该每次调用的提供方法,然后调用原始方法.

下面的代码说明了这种方法:

你的装饰者:

export function Foo(funcToCallEveryTime: (...args: any[]) => void)
{
    return (target: any, key: string, descriptor: any) => 
    {
        var originalMethod = descriptor.value; 

        descriptor.value =  function (...args: any[]) {
            funcToCallEveryTime(...args);
            return originalMethod.apply(this, args);
        }

        return descriptor;
    }
}
Run Code Online (Sandbox Code Playgroud)

和你用@Foo装饰器装饰的方法如下:

@Foo((...args: any[]) => { console.log("Before method call:", args[0]); })
private TestMethod(param: string): void
{
    console.log("Method call");
    //...
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.