Applying Javascript behaviours once in Drupal

Versions used: 

Drupal uses Drupal.behaviours as a replacement for jQuery.ready, but unlike jQuery.ready it can run multiple times during page execution or whenever new DOM elements are inserted into the document. This can be a problem when we want code inside the Behavior to run only once. This is important if you want to create a new instance of an object, for example. What I used to do in the past (for Drupal 6) was add a class to an element to know if the code had been processed or not:

Drupal.behaviors.myModule = function (context) {
  $('.mybehavior:not(.is-processed)', context).addClass('is-processed').each(function () {
    // any behavior is now applied once
  });
};

In Drupal 7 we have now been blessed with the once() function so we can do the same thing like this:

Drupal.behaviors.myModule = {
  attach: function (context, settings) {
    $('element', context).once('myModule', function () {
     // any behavior is now applied once
    });
  }
};

This ensures that the code will only fire once, even when using AJAX. Click here to view the once() JS code.