When implementing a Drupal behavior, a selector can use the 'context' parameter to let the behavior only apply to new elements. On page load the context is the document (I think), on ajax load it is the new ajax content.
Drupal.behaviors.my_behavior = {
attach: function attach(context, settings) {
$('.my-selector', context).each(function() {..});
Until now I thought that this alone is sufficient to make sure the behavior runs only once per element.
But in Drupal core and contrib, I see a lot of cases where context is used in combination with .once(), like so:
Drupal.behaviors.my_behavior = {
attach: function attach(context, settings) {
$('.my-selector', context).once(function() {..});
Is this ever necessary? Or is 'context' sufficient? And if it is not necessary, why is it used so much in core and contrib?
If it is necessary, does this also apply to click handlers? E.g. would the following cause duplicated click handlers in some cases?
Drupal.behaviors.my_behavior = {
attach: function attach(context, settings) {
$('.my-selector', context).click(function() {..});
NOTE: A secondary question would be if 'context' is still necessary if we use 'once()'. My answer to this is: Even if it is not necessary, it is still a good idea because it reduces the search space for jQuery on subsequent calls, thus reducing client-side energy consumption.
NOTE: I encountered this question on D7, but it might equally apply to D8.