我有一個呼叫該方法的點擊:
public clickEvent() {
this.createIframe().then((iframe) => { // Return iframe or create if is not before needed inside
// Async hard logic here
})
}
問題是當用戶點擊很多次clickEvent()時,它會觸發 Promise,然后觸發內部的硬邏輯。
如何避免點擊,直到里面的邏輯沒有完成?或者如果完成,則禁用內部呼叫邏輯?
uj5u.com熱心網友回復:
這些場景的良好做法,在 UX 級別上也很好,是在單擊后(以可見的方式)停用按鈕,并僅在操作完成后重新激活。iFrame 可以與其父級通信,以指示操作已完成。
這樣用戶就可以看到他們點擊了它,并且正在發生一些事情。如果您想進一步改進 UX,也可以添加微調器。
uj5u.com熱心網友回復:
如果您使用的是 Angular,我認為您可以將 click 事件轉換為 observable,然后使用各種運算子exhaustMap來實作此目的。
import { exhaustMap, fromEvent } from 'rxjs';
....
@ViewChild('btnId') btnElementRef!: ElementRef<HTMLButtonElement>;
ngAfterViewInit(): void {
fromEvent(this.btnElementRef.nativeElement, 'click')
.pipe(
exhaustMap(() => this.createIframe())
)
.subscribe((iframe) => {
// hard coded async logic here
});
}
);
這將忽略隨后的點擊,直到 Promise 首先解決。
此外,如果您想禁用按鈕并顯示某種加載指示器,您還可以添加一個變數來跟蹤流內使用tap
fromEvent(this.btnElementRef.nativeElement, 'click')
.pipe(
tap(() => isProcessing = true),
exhaustMap(() => this.createIframe())
)
.subscribe((iframe) => {
isProcessing = false;
// hard coded async logic here
});
uj5u.com熱心網友回復:
將createIframe其 Promise 快取起來(如作為實體屬性),如果存在則首先回傳它,而不是啟動另一個。例如:
// example function that creates the Promise
const createPromise = () => {
console.log('creating Promise');
return new Promise(resolve => setTimeout(resolve, 3000));
}
class SomeClass {
createIframe() {
if (this.iframePromise) return this.iframePromise;
this.iframePromise = createPromise();
return this.iframePromise;
}
clickEvent() {
this.createIframe().then((iframe) => {
console.log('clickEvent has received the Promise and is now running more code');
})
}
}
const s = new SomeClass();
button.onclick = () => s.clickEvent();
<button id="button">click to call clickEvent</button>
如果您還想防止// Async hard logic here多次單擊后運行多次,請改為為內部實體分配一些內容clickEvent。
// example function that creates the Promise
const createPromise = () => {
console.log('creating Promise');
return new Promise(resolve => setTimeout(resolve, 3000));
}
class SomeClass {
createIframe() {
return createPromise();
}
clickEvent() {
if (this.hasClicked) return;
this.hasClicked = true;
this.createIframe().then((iframe) => {
console.log('clickEvent has received the Promise and is now running more code');
})
}
}
const s = new SomeClass();
button.onclick = () => s.clickEvent();
<button id="button">click to call clickEvent</button>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/487196.html
標籤:javascript 有角度的
上一篇:如何在回圈中排列目標
