如何让JavaScript模态框关闭时返回Promise值控制计时器运行状态
模态框Promise交互实现方案
核心实现思路:将MODAL类的open方法改造为返回Promise实例,把Promise的resolve、reject方法挂载到模态框实例上,关闭模态框时根据操作类型触发对应状态,调用侧即可根据Promise返回结果执行不同的后续逻辑。
修改后的MODAL类代码
class MODAL{ constructor(){ this.modal_container = document.createElement("div") this.modal_container.classList.add("modal") document.querySelector("body").appendChild(this.modal_container) this.overlay = document.createElement("div") this.overlay.classList.add("overlay") this.modal_container.appendChild(this.overlay) this.content_container = document.createElement("div") this.content_container.classList.add("modal-content") this.modal_container.appendChild(this.content_container) this.boxContent = document.createElement("div") this.boxContent.classList.add("modal-box") this.content_container.appendChild(this.boxContent) // 存储Promise的resolve和reject方法 this.resolve = null this.reject = null this.events() } // 入参标识本次关闭是否为确认操作 close(isConfirm = false){ this.modal_container.parentNode.removeChild(this.modal_container); isConfirm ? this.resolve(true) : this.reject(false) } // open方法返回Promise供调用侧监听关闭状态 open(content){ this.boxContent.appendChild(content); return new Promise((resolve, reject) => { this.resolve = resolve this.reject = reject }) } // EVENTS events(){ this.closeEvent() } closeEvent(){ this.modal_container.addEventListener("click", e =>{ // 点击遮罩关闭默认按取消处理 if(!e.target.closest(".modal-box")){ this.close(false); } }) } }
修改后的Open函数代码
async function Open(issue){ issue.addEventListener("click", async () => { let content = document.createElement("div"); content.classList.add("rows"); let html = ` <div> <h1 class = "title">TITLE</h1> </div> <div> <input type = "text" placeholder = "מערכת"> </div> <div> <input type = "text" placeholder = "פורט"> </div> <div> <input type = "text" placeholder = "RIT"> </div> <div> <input type = "text" placeholder = "כמה זמן לקח"> </div> <div> <input type = "time" placeholder = "התחיל מ"> </div> <div> <input type = "time" placeholder = "נגמר ב"> </div> <!-- 新增操作按钮组 --> <div class="modal-actions"> <button class="confirm-btn">确认</button> <button class="cancel-btn">取消</button> </div> ` content.innerHTML = html timer.pause = true const modal = new MODAL() // 绑定按钮点击事件 content.querySelector('.confirm-btn').addEventListener('click', () => { modal.close(true) }) content.querySelector('.cancel-btn').addEventListener('click', () => { modal.close(false) }) try{ // 等待模态框确认关闭 await modal.open(content) // resolve状态恢复计时器 timer.pause = false }catch{ // reject状态执行元素删除逻辑 issue.remove() // 可替换为实际需要的删除逻辑 } }) }
逻辑说明
- 点击确认按钮关闭模态框会触发Promise的resolve状态,进入try分支恢复计时器运行
- 点击取消按钮/点击遮罩关闭模态框会触发Promise的reject状态,进入catch分支执行元素删除逻辑
内容的提问来源于stack exchange,提问作者DDHost
相关产品推荐
相关产品推荐

