使用EventListener解析一个promise [英] resolving a promise with EventListener

查看:70
本文介绍了使用EventListener解析一个promise的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个弹出式div,我想对动画有一个承诺,所以我可以在弹出结束后做一些事情。

I am working on a popup div and I would like to have a promise attached to the animation so I can do something after the popup ended.

我的做法是不起作用,因为我找不到将承诺传递给事件处理程序上的函数的方法。似乎你不能在这里使用bind。我已经尝试了,虽然我可以解决这个承诺,但我无法删除事件处理程序

My approach does not work because I could not find a way to pass the promise to the function on the event handler. Seems you cannot use bind here. I have tried and although I can resolve the promise, I cannot remove the event handler

这里有什么不同的解决方案?

What would be a different solution here?

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));
    }
}


推荐答案

你不需要将promise传递给事件处理程序,你需要传递 resolve 回调:

You do not need to pass the promise to the event handler, you need to pass the resolve callback:

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

// [...]

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

这看起来有点难看,也许你可以看看这样的东西:

This looks a bit ugly to me, maybe you can look at something like this:

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();
    });
});

这篇关于使用EventListener解析一个promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆