Вернуть «True» или «False» значения в соответствии с нажатыми кнопками - Toastr, JS (no angular) - PullRequest
0 голосов
/ 29 апреля 2020

Я построил функцию, которая создает предупреждение с помощью Toastr. (запись в JS, без использования Angular).

Он спрашивает, хотите ли вы удалить файл.

, если пользователь нажимает кнопку «ДА», я хочу вернуть логическое значение : "True"

, если пользователь нажимает кнопку "NO", я хочу вернуть логическое значение: "False"

Проблема:

Я не получил логическое значение назад, когда я вызвал функцию fileAlert.

Вызывающая функция:

 async function noticeUser() {
                let promise = new Promise(() => {
                    fileAlert();
                });
                let result = await promise;
                console.log("The result was: "+result); //after execution: result is empty 
            };

Функция fileAlert ():

<script>

        function fileAlert() { 

                var userAnswer = toastr.warning('Are you sure you want to delete the file?<br /><br /><button type="button" id="yesDelete" class="btn clear">Yes</button>&nbsp;<button type="button" id="noDelete" class="btn clear">No</button>', "Warning");
                var userSaid = true;
                toastr.options = {
                    "closeButton": false,
                    "allowHtml": true,
                    onShown: function (toast) {

                        $('#yesDelete').click(function () {
                            console.log('user clicked yes - he wants to delete the file')
                            toastr.clear(userAnswer);
                            return userSaid;
                        });
                        $('#noDelete').click(function () {
                            console.log('user clicked no - he doesnt want to delete the file')
                            //Deleting warning message from screen.
                            toastr.clear(userAnswer);        
                            //Returning False so that deletion procedure will not occur
                            userSaid= false;
                            return userSaid;
                        });                      

                    },
                    "debug": false,
                    "newestOnTop": false,
                    "progressBar": false,
                    "positionClass": "toast-top-right",
                    "preventDuplicates": false,
                    "showDuration": "300",
                    "hideDuration": "1000",
                    "timeOut": 0,
                    "extendedTimeOut": 0,
                    "showEasing": "swing",
                    "hideEasing": "linear",
                    "showMethod": "fadeIn",
                    "hideMethod": "fadeOut",
                    "tapToDismiss": false
            }  

        };        
    </script>

1 Ответ

0 голосов
/ 01 мая 2020

Мое решение состоит из 2 шагов:

1) Я удалил onShown внутри toastr.options и вызвал функции onClick после определения toastr.options.

2) Я изменил функцию noteUser на быть:

fileAlert().then(result => {
            console.log(result);
            if (result == true) {.....}   });

Функция fileAlert после исправления:

function fileAlert() { 
        return new Promise((resolve,reject)=>{

            var userAnswer = toastr.warning('Are you sure you want to delete the file?<br /><br /><button type="button" id="yesDelete" class="btn clear">Yes</button>&nbsp;<button type="button" id="noDelete" class="btn clear">No</button>', "Warning");               
            toastr.options = {
                "closeButton": false,
                "allowHtml": true,                  
                "debug": false,
                "newestOnTop": false,
                "progressBar": false,
                "positionClass": "toast-top-right",
                "preventDuplicates": false,
                "showDuration": "300",
                "hideDuration": "1000",
                "timeOut": 0,
                "extendedTimeOut": 0,
                "showEasing": "swing",
                "hideEasing": "linear",
                "showMethod": "fadeIn",
                "hideMethod": "fadeOut",
                "tapToDismiss": false
            }
            $('#yesDelete').click(function () {
                console.log('user clicked yes - he wants to delete the file')
                toastr.clear(userAnswer);
                resolve(true);
            });
            $('#noDelete').click(function () {
                console.log('user clicked no - he doesnt want to delete the file')
                //Deleting warning message from screen.
                toastr.clear(userAnswer);
                //Returning False so that deletion procedure will not occur                 
                resolve(false);
            });              
        });               
    };
...