What is the difference between the following ways of using the ON and OFF methods of jQuery

6

1 - Used to use this way:

$(document).off('evento', 'elemento', nomeFuncao);
$(document).on('evento', 'elemento', nomeFuncao);

2 - But recently I used it that way and it worked the same way.

$(document).off().on('evento', 'elemento', function() {});

In the second example I did not use any kind of identifier for the off method. But even so he removed only the correct event from the obj document.

I wonder if the second form of use is correct as well. Or is it a bad practice?

    
asked by anonymous 01.08.2016 / 19:32

2 answers

1
The .off() is mainly used to prevent duplication of the same action, see example, SEM .off() :

function button(e){

  if($(e).hasClass('comOff')){
    $(e).off();
  }
  
  $(e).on('click', function() {
        button($(this));
        alert($(this).text());
  });

}


button('.semOff');
button('.comOff');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><buttonclass="semOff">SEM OFF</button>
<br>
<hr>
<button class="comOff">COM OFF</button>

In this example, which is not one of the best, when you click "OFF OFF" more than once will display more than one alert. This is because the previous action was not turned off, so one more will be added. When you use .off() you will remove any .on() that was previously added.

When you use $(document).off() , it means that ALL .on() applied to document will be removed, when you specify $(document).off('evento', 'elemento', nomeFuncao); you will only remove it!

That's the difference.

I particularly prefer to use $('div button.salvar').on('click', [...]) for example, instead of using document .

    
02.08.2016 / 10:07
5

Yes, the second form is correct, as per documentation . It removes all listeners from element events that have been added with on - in case of your example, all listeners of document will be removed.

    
01.08.2016 / 19:38