EventListenerでPromiseを解決する 質問する

EventListenerでPromiseを解決する 質問する

私はポップアップ div に取り組んでおり、ポップアップが終了した後に何かを実行できるように、アニメーションに promise を添付したいと考えています。

私のアプローチは、イベントハンドラの関数にプロミスを渡す方法が見つからなかったため機能しません。ここではbindを使用できないようです。試してみましたが、プロミスは解決できましたが、イベントハンドラを削除することはできません。

ここで別の解決策は何でしょうか?

function EventListenerForPopUp() {
    this.removeEventListener("animationend", EventListenerForPopUp );
    this.Show.resolve();
}   

function ShowHideDiv() {        
    this.Show = function () { 
        return new Promise(function(resolve, reject) {
            this.Div.addEventListener("animationend", EventListenerForPopUp, false);
        }.bind(this));
    }
}

ベストアンサー1

イベント ハンドラーに promise を渡す必要はありませんが、resolveコールバックを渡す必要があります。

function EventListenerForPopUp(resolve) {
            this.removeEventListener("animationend", EventListenerForPopUp );
            resolve();
}   

// [...]

        return new Promise(function(resolve, reject) {
            this.Div.addEventListener("animationend", function() {
                EventListenerForPopUp.call(this, resolve);
            }, false);

これはちょっと見苦しいと思いますので、次のようなものを見てみてはいかがでしょうか。

var div = this.Div;
return new Promise(function (resolve) {
    div.addEventListener("animationend", function animationendListener() {
        div.removeEventListener("animationend", animationendListener);
        //call any handler you want here, if needed
        resolve();
    });
});

おすすめ記事