简体   繁体   English

如何使用 Promise 在 JS 中实现自定义“确认”提示

[英]How to implement a custom 'confirm' prompt in JS using promises

This is the base code这是基本代码

$(".add-item").click(function() {
  var flag;
  var ask_about_flag = // some logic ... 
  if (ask_about_flag == true) {
    if (confirm("Add with a flag?") == true) {
      flag = true
    } else {
      flag = false
    }
  } 
  addItem(flag)
})

What I want to do though, is build a robust modal containing specific instructions about how to answer the 'Add with a flag?'不过,我想做的是构建一个强大的模式,其中包含有关如何回答“带标志添加?”的具体说明。 question being posed.提出的问题。 Within the modal, there will be 2 button elements for 'Yes' vs 'No'.在模式中,“是”与“否”将有 2 个按钮元素。 So think of this as a basic modal (using Bootstrap):因此,将其视为基本模式(使用 Bootstrap):

<div class="modal fade" tabindex="-1" role="dialog" aria-labelledby="flag_modal" aria-hidden="true" id="flag_modal">
    <div class="modal-dialog modal-lg" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h2 class="modal-title serif text-center">
            Add with a flag?
          </h2>
        </div>
        <div class="modal-body">
          <!-- detailed instructions -->
          <button id="yes" class="btn btn-lg">Yes</button>
          <button id="no" class="btn btn-lg">No</button>
        </div>
      </div>
    </div>
</div>

Like the default confirm alert, the UX is that when add-item is clicked, if the not-included logic calculates that ask_about_flag is true, this modal pops up, and the code doesn't proceed to call addItem until user selects either #yes or #no to set the value of the flag.与默认的confirm警报一样,UX 是当点击add-item时,如果未包含的逻辑计算出ask_about_flag为 true,则弹出此模式,并且代码不会继续调用addItem ,直到用户选择#yes#no设置标志的值。

However, it's also possible that upon add-item click, the not-included logic calculates that ask_about_flag is false, so the modal doesn't show and addItem is called ( flag = null in this case).但是,也有可能在单击add-item时,未包含的逻辑计算出ask_about_flag为 false,因此不显示模态并调用addItem (在这种情况下为flag = null )。

Because of this, I think it makes sense for code organizing to keep addItem function call within the add-item click, rather than push it down into the button handlers (to be clear code below would work)正因为如此,我认为代码组织将addItem function 调用保留在add-item单击中是有意义的,而不是将其向下推到按钮处理程序中(要清楚,下面的代码会起作用)

$(".add-item").click(function() {
  var ask_about_flag = // some logic ... 
  if (ask_about_flag == true) {
    $("#flag_modal").show()
  } 
  addItem()
})

$("#yes").click(function() {
  addItem(true)
})

$("#no").click(function() {
  addItem(false)
})

I want to do something instead like:我想做一些事情,比如:

$(".add-item").click(function() {
  var flag;
  var ask_about_flag = // some logic ... 
  if (ask_about_flag == true) {
    // pop up modal to ask user to set value of flag
  } 
  // wait to execute until value of flag is set, if needed
  addItem(flag)
})

Seems like Promises are the way (let me know if not,), but that's still pretty new to me.似乎Promises是一种方式(如果没有,请告诉我),但这对我来说仍然很新。 so I took a stab with the below.所以我用下面的东西刺了一下。 Working up until when I click a yes or no button where I get Uncaught TypeError: promise.resolve is not a function工作到当我单击yesno按钮时,我得到Uncaught TypeError: promise.resolve is not a function

var promise; // declare so that it's available both from within `add-item` and `button` handlers

$(".add-item").click(function() {
  promise = new Promise(function(resolve, reject) { 
    var ask_about_flag = // some logic ... 
    if (ask_about_flag == true) {
      $("#flag_modal").modal("show")
    } else {
      resolve(null)
    }
  })

  promise.then(function(flag) {
    // flag is the parameter passed to resolve
    addItem(flag)
  })
})

$("#yes").click(function() {
  promise.resolve(true)
})

$("#no").click(function() {
  promise.resolve(false)
})

FIDDLE: https://jsfiddle.net/0g76ce5s/小提琴: https://jsfiddle.net/0g76ce5s/

Example how to implement logic:示例如何实现逻辑:

    <script>
        function addItem(flag) {
            //--Your logic here when press yer or no, flag var can be true/false
        }
        $(function() {
            $("#yes").click(function() {
                addItem(true);
            });
    
            $("#no").click(function() {
                addItem(false);
            });
        }
    </script>
    <button onClick="$('#flag_modal').show();return false;">Show modal for confirmation</button>

Actually, I prefer your first approach as it is more separation of concerns.实际上,我更喜欢您的第一种方法,因为它更多地分离了关注点。

However if you want to do the Promise approach, what you need to pass is the resolve function instead of the Promise.但是,如果您想执行 Promise 方法,您需要通过resolve function 而不是 Promise。

Example below:下面的例子:

 var resolveGlobal; // declare so that it's available both from within `add-item` and `button` handlers $(".add-item").click(function () { promise = new Promise(function (resolve, reject) { var ask_about_flag = true; if (ask_about_flag) { $("#flag_modal").modal("show"); resolveGlobal = resolve; } else { resolve(null); } }); promise.then(function (flag) { // flag is the parameter passed to resolve addItem(flag); }); }); $("#yes").click(function () { resolveGlobal(true); }); $("#no").click(function () { resolveGlobal(false); }); function addItem(flag) { console.log(flag); }
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width. initial-scale=1:0" /> <title>Document</title> <script src="https.//code.jquery.com/jquery-3.6.0.min:js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous" ></script> <link rel="stylesheet" href="https.//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min:css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous" /> <script src="https.//code.jquery.com/jquery-3.2.1.slim.min:js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous" ></script> <script src="https.//cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min:js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous" ></script> <script src="https.//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min?js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous" ></script> </head> <body> <div id="box"> <div class="modal fade" tabindex="-1" role="dialog" aria-labelledby="flag_modal" aria-hidden="true" id="flag_modal" > <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <h2 class="modal-title serif text-center"> Add with a flag? </h2> </div> <div class="modal-body"> <!-- detailed instructions --> <button id="yes" class="btn btn-lg">Yes</button> <button id="no" class="btn btn-lg">No</button> </div> </div> </div> </div> <button class="add-item">Add item</button> </div> </body> </html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM