简体   繁体   English

覆盖JQuery先前的回调函数

[英]Override JQuery previous callback function

I am having this problem with a callback function. 我在使用回调函数时遇到了这个问题。 I have this function to display an alert message, and it has a callback (okcallback) to be executed if it is provided: 我具有此功能来显示警报消息,并且如果提供的话,它具有要执行的回调(okcallback)

function ErrorAlert(msg,okcallback) {

    ISAPP.ui.loader_modal_header.html('<h4 class="modal-title">'+ label.alertLabel +'</h4>');
    ISAPP.ui.loader_modal_body.html(msg);
    ISAPP.ui.loader_modal_footer.html('<div class="clearfix ">' +
              '<a id="modal-alert-close" class="btn green pull-right">' +
                '<label>'+ label.acceptLabel +'</label>' +
                ' <i class="fa fa-check-circle"></i>' +
              '</a>' + 
            '</div>');
    ISAPP.ui.loader_modal_header.show();
    ISAPP.ui.loader_modal_body.show();
    ISAPP.ui.loader_modal_footer.show();
    ISAPP.ui.loader_modal.modal('show');

    $(document).on('click','#modal-alert-close',
            function(){
                ISAPP.ui.loader_modal_footer.html('');
                ISAPP.ui.loader_modal.modal('hide');
                if(okcallback){
                    okcallback();
                }
            }
    );      
}

It is working fine when I use it with callback or no callback at first execution of the function. 当我在函数首次执行时将其与回调一起使用或没有回调时,它工作正常。 But when it is being executed the 2nd time, whatever the callback on the previous execution will carry over to the 2nd execution even though there's no callback function on the 2nd execution. 但是,当第二次执行时,即使第二次执行没有回调函数,上一次执行的回调也将继续执行到第二次执行。

Sample: 样品:
1st execution (will go to blank after closing the message) 第一次执行(关闭消息后将变为空白)

ErrorAlert("Pincode has been sent to " + email,
            function(){
                location.href = "#/blank";  
            }
    );

2nd execution (should not do anything after closing message) 第二次执行(关闭消息后不应执行任何操作)

ErrorAlert("Username is mandatory");

But what's happening is, the function still goes to "#/blank" which means it runs the previous callback function. 但是正在发生的是,该函数仍然转到“#/ blank”,这意味着它将运行先前的回调函数。 Why is this happening? 为什么会这样呢? How do I prevent this from happening? 如何防止这种情况发生?

Thank you. 谢谢。

I'll assume you don't have multiple times the same id in your page, that is your first dialog is being closed before you open a new one. 我假设您的页面中没有相同的ID多次,也就是说,在打开新对话框之前,您的第一个对话框已关闭。

You could unbind using off but there's no reason to use delegation here. 您可以使用off取消绑定off但是这里没有理由使用委派。 A simple solution would be to bind to your newly added element instead of the whole document. 一个简单的解决方案是绑定到您新添加的元素,而不是整个文档。 This way, the binding will be removed with the element. 这样,绑定将与元素一起移除。

Replace 更换

$(document).on('click','#modal-alert-close'

with

$('#modal-alert-close').on('click',

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

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