bind event only once

前端 未结 13 2100
予麋鹿
予麋鹿 2020-12-05 03:45

I have the following code:

function someMethod()
{
  $(obj).click(function {});
}

someMethod is called twice and thus click event is binded

相关标签:
13条回答
  • 2020-12-05 04:17

    I was also trying to use off and on method of jquery for binding event only once with the dom element which does not exists yet or the dom element is not yet created.

    $('.select').off('event').on('event', 'selector', function(e){ // });
    

    This code was not working properly

    I came across a very lucrative method that is 'one' method. It is very useful when you want to bind an event only once.

    You can find the document here http://api.jquery.com/one/

    This is same as method 'on' but different with its behavior with not to stick with the event for multiple selectors.

    $('body').one('click', 'selector', function(){ // do your stuff here });
    
    0 讨论(0)
  • 2020-12-05 04:19

    If you can apply it, probably want to take a look at event.preventDefault and event.stopPropagation OR unbind and bind each time, within your method like

    function someMethod()
    {
      $(obj).off('click').on('click', function(e) {
        // put your logic in here 
      });
    }
    
    0 讨论(0)
  • 2020-12-05 04:20

    You can achieve this with pure JS, using addEventListener method and his once option

    target.addEventListener('click', handler, {once: true});
    
    0 讨论(0)
  • 2020-12-05 04:24

    You can add css class to the binded elements and then filter them out:

    function someMethod()
    {
        $(obj).not('.click-binded')
              .click(function {})
              .addClass('click-binded');
    }
    

    This method may be used also for plugins:

      $(obj).not('.datetimepicker-applied')
            .datetimepicker()
            .addClass('datetimepicker-applied');
    
    0 讨论(0)
  • 2020-12-05 04:27

    There is no built in method to determine if you have already bound this particular function. You can bind multiple click functions to an object. For example:

    $('#id').bind('click', function(){
    alert('hello');
    });
    
    
    $('#id').bind('click', function(){
    alert('goodbuy');
    });
    

    if you do the above when the object is clicked it will alert hello then goodbye. To make sure only one function is bound to the click event unbind the click event handler then bind the desired function like this:

    $(obj).unbind('click').bind('click', function(){... });
    
    0 讨论(0)
  • 2020-12-05 04:28

    jQuery makes calling some function possible only once pretty easy:

    function someMethod()
    {
    
         $(obj).click(function() {});
          this.someMethod = $.noop;
    }
    
    0 讨论(0)
提交回复
热议问题