【发布时间】:2021-11-28 21:12:53
【问题描述】:
代码也可在fiddle 获得。这是我项目中最小的可重现样本。
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<button class="alert">Do stuff</button>
</body>
<template id="modal_template">
<div class="modal_background">
<div class="modal_content">
<h2 class="modal_header"></h2>
<p class="modal_message"></p>
<button class="modal_button modal_accept_button"></button>
</div>
</div>
</template>
</html>
async function display_modal(title, message, button_label = "Accept") {
// resolve promise when accept is clicked
return new Promise((resolve) => {
// create a modal from template
const temp = document.querySelector("#modal_template");
let clone = temp.content.cloneNode(true);
clone.querySelector(".modal_header").innerText = title;
clone.querySelector(".modal_message").innerText = message;
// create an accept button
const button = clone.querySelector(".modal_accept_button");
button.innerText = button_label;
button.addEventListener("click", (e) => {
// On click, delete modal and resolve the promise
const modal_background = e.srcElement.parentNode.parentNode;
modal_background.parentNode.removeChild(modal_background);
resolve();
});
document.body.appendChild(clone);
});
}
window.onload = () => {
const alert = document.querySelector(".alert");
alert.addEventListener("click", () => {
display_modal("Alert", "Important message", "Accept").then(console.log("Accept button clicked"));
});
}
预期行为
- 用户点击“做事”按钮
- Modal 出现并提供一些按钮供用户点击。
- 模态框上的按钮被点击。
-
console.log("Accept button clicked")正在运行,模式已被删除。
实际行为
- 用户点击按钮“做事”。
console.log("Accept button clicked")已运行。 - Modal 出现并提供一些按钮供用户点击。
- 模态框上的按钮被点击。
- 模态框被删除。
当前代码:
window.onload = () => {
const alert = document.querySelector(".alert");
alert.addEventListener("click", () => {
display_modal("Alert", "Important message", "Accept").then(console.log("Accept button clicked"));
});
}
当前的行为感觉如下:
window.onload = () => {
const alert = document.querySelector(".alert");
alert.addEventListener("click", () => {
display_modal("Alert", "Important message", "Accept");
console.log("Accept button clicked");
});
}
为什么会这样?
【问题讨论】:
-
.then接受一个函数。console.log("Accept button clicked")不是函数。 -
@SebastianSimon 谢谢,忽略了
-
@PavelSkipenes - 但为什么是 Promise 对象?该代码没有任何异步。
-
请查看The Explicit Construction Anti-Pattern 的全部内容。具体来说,将其用作美化的事件发射器或回调实用程序。
标签: javascript promise addeventlistener