Popup.prototype.requestAlert = function(serviceRequest) {
return new Promise(function(resolve, reject){
alertMessage.innerHTML = serviceRequest.message;
alert.classList.remove('hidden');
alertOK.addEventListener('click', function(event){
alertOK.removeEventListener('click'); // remove here???
alert.classList.add('hidden');
reject(serviceRequest);
});
});
};
Popup.prototype.requestConfirm = function(serviceRequest) {
return new Promise(function(resolve, reject){
confirmMessage.innerHTML = serviceRequest.message;
confirm.classList.remove('hidden');
confirmOK.addEventListener('click', function(event){
confirmOK.removeEventListener('click');
confirmCancel.removeEventListener('click');
confirm.classList.add('hidden');
resolve(serviceRequest);
});
confirmCancel.addEventListener('click', function(event){
confirmOK.removeEventListener('click');
confirmCancel.removeEventListener('click');
confirm.classList.add('hidden');
reject(serviceRequest);
});
});
};
如何动态添加事件处理程序,然后在函数范围内删除它,这样我仍然可以访问返回的resolve
的{{1}}和reject
?
修改:
我添加了确认相关代码,不同之处在于需要动态添加和删除OK和Cancel的事件。
答案 0 :(得分:0)
removeEventListener
传递对应该删除的处理程序的引用。为您的处理程序命名并将其传递给removeEventListener
:
alertOK.addEventListener('click', function handler(event){
alertOK.removeEventListener('click', handler);
// or better: this.removeEventListener('click', handler);
alert.classList.add('hidden');
reject(serviceRequest);
});
对于另一个例子,在promise回调的范围内创建命名函数:
return new Promise(function(resolve, reject){
confirmMessage.innerHTML = serviceRequest.message;
confirm.classList.remove('hidden');
function ok() {
confirmOK.removeEventListener('click', ok);
confirmCancel.removeEventListener('click', cancel);
// ...
}
function cancel() {
confirmOK.removeEventListener('click', ok);
confirmCancel.removeEventListener('click', cancel);
// ...
}
confirmOK.addEventListener('click',ok);
confirmCancel.addEventListener('click',cancel);
});