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
.