抱歉,如果我的问题很愚蠢,但我们的应用程序正面临延迟问题。
KEYPRESS 事件处理程序是罪魁祸首。我们在整个应用程序中使用下面的指令。它通过 HostListener
检查 KeyPress
。按下按键时,此指令使用正则表达式检查值,如果条件为假,则执行 preventDefault
。
private regexMap = { // add your own
'999': /^([0-9]){0,3}$/g,
'9999': /^([0-9]){0,4}$/g,
...
...
}
@HostListener('keypress', [ '$event' ])
public nInput(event: KeyboardEvent) {
// Allow Backspace, tab, end, and home keys
if (this.specialKeys.indexOf(event.key) !== -1) {
return;
}
this.pattern = this.regexMap[this.validationFormat];
const current: string = this.el.nativeElement.value;
const next: string = current.concat(event.key);
if (next && !String(next).match(this.pattern)) {
event.preventDefault();
}
}
我不确定如何解决这个问题。 debounceTime
会解决这个问题吗?我不确定如何向此方法添加去抖动。请有人帮我解决这个问题。
最佳答案
修复了 DebounceTime 的问题 :) 刚刚通过帮助主题添加了去抖动时间。 基本上,当用户输入一些东西时,它会停止所有操作,然后将 EVENT(按键值)发送到 SUBJECT,并在 subject debounce Time 等待 300ms,然后进行功能测试
private keyPressed = new Subject();
private subscription: Subscription;
private pattern: RegExp;
private regexMap = { // add your own
'999': /^([0-9]){0,3}$/g,
'9999': /^([0-9]){0,4}$/g,
...
...
}
private specialKeys: string[] = ['Backspace', 'Tab', 'End', 'Home'];
constructor(private el: ElementRef) {
}
public ngOnInit() {
this.subscription = this.keyPressed.pipe(debounceTime(300)).subscribe(
(event) => this.checkRegExpression(event)
);
}
public ngOnDestroy() {
this.subscription.unsubscribe();
}
@HostListener('keypress', ['$event']) public nInput(event: KeyboardEvent) {
event.preventDefault();
event.stopPropagation();
this.keyPressed.next(event);
}
private checkRegExpression(event) {
if (this.specialKeys.indexOf(event.key) !== -1) {
return;
}
this.pattern = this.regexMap[this.validationFormat];
const current: string = this.el.nativeElement.value;
const next: string = current.concat(event.key);
if (next && !String(next).match(this.pattern)) {
event.preventDefault();
}
}
关于javascript - Angular 4/5 中的事件处理程序性能问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49065228/