简体   繁体   English

元素上的click事件重复绑定解除绑定

[英]Repeated binding unbinding of click event on element

I'm kind of confused, I want to know binding and unbinding event on the same element is better or I should use a flag (something like 'inProgress'). 我有点困惑,我想知道同一元素上的绑定和取消绑定事件更好,或者我应该使用一个标志(例如“ inProgress”之类的东西)。

I have a scenario where I have to prevent an operation or event from happening if one operation is already in process, for eg. 我有一种情况,例如,如果一项操作已在进行中,则必须阻止一项操作或事件的发生。

I have an anchor tag and I've bind an event to that anchor tag and that event handles some ajax functionality like fetching data and updating certain part of the page, what I want is to stop repeated click on the anchor tag from happening so that once the first click has happened on the anchor tag wait till the response comes from the server and the part of the page is updated, my confusion lies whether i should unbind the event once the click happens and bind the same handler again once the response is handled or should I setup a flag to check if any handler is in progress and set the flag false once the response is handled? 我有一个锚标记,并且已经将事件绑定到该锚标记,并且该事件处理了一些ajax功能,例如获取数据和更新页面的某些部分,我想要的是阻止重复单击锚标记,以免发生这种情况一旦锚标记上的第一次单击发生,直到响应来自服务器并且页面的一部分被更新,我的困惑就在于是否应在单击发生后取消绑定该事件,并在响应发生后再次绑定同一处理程序处理还是应该设置一个标志来检查是否有任何处理程序正在进行中,并在响应被处理后将标志设置为false? which of the way would be efficient performance wise? 哪种方法才是有效的性能明智的选择?

Any help/suggestion is much appreciated! 任何帮助/建议都非常感谢!

Thanks 谢谢

use a flag! 使用标志!

it's better to use some boolean variable and check if you are allowed that action rather than calling bind and unbind (which is additional overhead). 最好使用一些布尔变量并检查是否允许执行该操作,而不是调用bind和unbind(这是额外的开销)。

if you use jQuery, you can use the data() to store data on that anchor. 如果使用jQuery,则可以使用data()在该锚点上存储数据。

like: 喜欢:

$('.testLink').on('click',function(){

    //reference link
    var link = $(this);

    //check data
    data = link.data('amIallowed');

    //if no data existed yet
    if(!data){

        //set data and make it false to prevent further requests
        link.data('amIallowed',{
            allowRequest : false
        });

        //lets do ajax
        doAjax();    
    }
    else{ //if there was data

        //and we were allowed
        if(data.allowRequest){
            doAjax(link);    
        }   
    }
});

//do ajax stuff here
function doAjax(link){
    $.post('url',{param:val},function(){

        //revert to true after request
        link.data('amIallowed',{
            allowRequest : true
        });

    });
}

if you don't use jQuery, you can still do the same feat using simple JS. 如果您不使用jQuery,仍然可以使用简单的JS来完成相同的功能。 jQuery uses " expando-properties " to bind data onto elements. jQuery使用“ expando-properties ”将数据绑定到元素上。 if you can do with expando-props, use variables instead. 如果可以使用expando-props,请改用变量。

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

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