Future-Proofing Code by Using Array with Once(): Mark Conroy Explains

a person working in computer
Unsplash

Mark Conroy's blog post titled "How to use once() in Drupal" provides practical insights into the application of the 'once()' library in Drupal. These insights are shared through a concise and compelling code snippet.

Once, a Drupal libraryavailable on npmensures your JavaScript only runs once when working on any item. The provided code snippet is a valuable guide for developers aiming to ensure the precise execution of their JavaScript code for a designated item.

Mark adopts a pragmatic approach by assigning the result of 'once()' to the variable 'editFrequencys,' always obtaining an array, even when dealing with a single item. This approach minimizes potential issues in case additional instances of the targeted element emerge on the webpage in the future.

const editFrequencys = once('allEditFrequencies', '.edit-frequency', context);

editFrequencys.forEach(editFrequency => {
  editFrequency.on('change', function() {
    $.ajax({
      method: "POST",
      url: "/frequency-select",
      data: { name: "John", location: "Boston" },
      dataType: "json"
    })
      .done(function( data ) {
        console.log("It's done!");
        console.log(data);
      });
  });
});

Within the presented example, the arguments in the first line fulfill distinct roles in the process. The label 'allEditFrequencies' acts as a distinctive identifier, linking the targeted DOM element to the 'once()' function. This label is then associated with a data attribute in the DOM, enabling the seamless identification of the specified item's relevant 'once()' function.

The inclusion of 'context' as a parameter in the code signifies the method used to locate the array of elements, with a preference for this over 'document' in Drupal to accommodate dynamic updates, particularly in scenarios involving AJAX.

Mark's practical explanation demystifies the usage of 'once().' It underscores the significance of future-proofing code by working with arrays, a prudent choice even when anticipating a solitary item on the webpage. Read more here.

Disclaimer: The opinions expressed in this story do not necessarily represent that of TheDropTimes. We regularly share third-party blog posts that feature Drupal in good faith. TDT recommends Reader's discretion while consuming such content, as the veracity/authenticity of the story depends on the blogger and their motives. 

Note: The vision of this web portal is to help promote news and stories around the Drupal community and promote and celebrate the people and organizations in the community. We strive to create and distribute our content based on these content policy. If you see any omission/variation on this please let us know in the comments below and we will try to address the issue as best we can.

Advertisement Here

Upcoming Events

Latest Opportunities

Advertisement Here