javascript-Angular 4/5中的事件处理程序性能问题
作者:互联网
抱歉,如果我的问题很傻,但是我们在应用程序中遇到了延迟问题.
KEYPRESS事件处理程序是罪魁祸首.我们在整个应用程序中使用以下指令.它通过HostListener检查KeyPress.按下键时,此伪指令使用regexp检查值,并且如果condition为false则执行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,并在主体反跳时间中等待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();
}
}
标签:angular,angular5,javascript 来源: https://codeday.me/bug/20191109/2012593.html