By technicalknockout on
Drupal javascript api ( http://drupal.org/node/756722 ) shows context & settings as parameters in the behaviors attach examples, but I've never seen an explanation of 'context'. Using console.log I see a large object literal with tons of keys, but how is it populated? Can you rely on certain key/value pairs always being there? Is it supposed to interact with jQuery in a certain way? Does anyone use this 'context' in practice and how is it helpful for you? Just trying to improve my drupal js understanding and maybe gather some info for that doc page ...
Comments
This link may help you https:
This link may help you https://www.lullabot.com/articles/understanding-javascript-behaviors-in-drupal
The context is the piece of
The
contextis the piece of the DOM that has been rendered beforeDrupal.behaviorsare invoked.Drupal.behaviorsis the Drupal version of an onload event handler - aka it's somewhat equivalent to Javascript'swindow.onload()and jQuery's$(document).ready(). However, Drupal behaviors differs in that it's not just invoked when the DOM is loaded, but also after new DOM elements have been added using Drupal's AJAX API. For example, when an element is added to the DOM using the Form API's #ajax property, after the new form elements are added into the page, Drupal will invokeDrupal.behaviorsso that event handlers can be attached to the new elements.The
contextis the part of the DOM that has just been loaded. On initial page load, it will be the entire document. On subsequent AJAX loads, it will be the part of the DOM that was just loaded.So, consider the following working code:
Every time new elements are inserted into the DOM, the entire DOM is parsed for
$(".some_element"). This is inefficient though, as the handlers would have already been attached on page load to any elements. Instead, we can limit the parsing to the newly inserted elements in thecontext, rather than the entire DOM:Now, instead of searching the entire DOM for
.some_element, only the newly inserted DOM elements are parsed for .some_element, making the code more efficient.As a side note, this removes the necessity of using jQuery event handlers such as
$.on(), that wait for elements to appear in the DOM and attach event handlers to them. This is because the combination ofDrupal.behaviorswith$.once()ensures that event handlers will always be attached to new elements when they are loaded by AJAX, and only attached a single time, removing any necessity for watchers like$.on().Contact me to contract me for D7 -> D10/11 migrations.