【发布时间】:2017-07-12 22:10:44
【问题描述】:
其目标是一种非侵入性技术,用于跟踪用户对所需组件行为的操作...点击和其他内容。
我喜欢装饰器如何修改行为,但我不确定这是不可能的,还是我做错了。
如果这行得通,它基本上就像原始事件处理程序的包装器一样。只需通过处理程序上的装饰,我就可以轻松地跟踪和取消跟踪事件。但我的目标是不要用这个用户跟踪层“弄脏”处理程序逻辑。同样方便的是,使用某些组件上下文调用装饰器,并且不需要显式编码上下文。该上下文信息可能对日志记录有用。
app.component.ts
import { Component } from '@angular/core';
import { CaptureUserEvent } from 'app/user-action-tracker';
@Component({
template: `
<h1>
{{title}}
</h1>
<a href="#" (click)="setTitleText($event)">Test</a>
`,
selector: 'app-root',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
title = 'app works!';
getElementText(elt:HTMLElement) {
return elt.innerText;
}
@CaptureUserEvent
setTitleText(ev:Event):void {
console.log('called setTitleText');
let newText = this.getElementText(<HTMLElement>ev.target);
this.title = newText;
}
}
user-action-tracker.ts
function CaptureUserEvent(cls, methodName, propertyDefinition):any {
var oldMethod = cls[methodName];
// this ultimately doesn't work... the AppComponent class retains the original function when it runs
cls[methodName] = function (ev:Event) {
console.log('called wrapper');
// log event...
oldMethod(ev);
};
}
export {
CaptureUserEvent
}
有没有正确的方法可以做到这一点,或者有类似的方法可以实现相同的目标?
【问题讨论】: