Anonymous Vs. Declared Callback Functions In Sharepoint Jsom

Definition of Callback Functions

A callback function is a function that is passed as an argument to another function to be executed after an asynchronous operation completes. In JavaScript, functions are first-class objects that can be passed around and used in the same way as other objects.

In SharePoint’s JavaScript object model (JSOM), many methods work asynchronously, meaning they return immediately without waiting for the operation to complete. To handle the result of an async operation, callback functions are used.

Anonymous Callback Functions

What are Anonymous Functions

Anonymous functions in JavaScript do not have an explicit name identifier. They are inline function expressions not bound to an identifier. An anonymous function can be assigned to a variable or passed to another function, but the function itself is nameless.

const myFunction = function() {
  // function body
};

The above function expression is anonymous. The function is assigned to the myFunction variable, but the function itself has no name property or identifier.

Using Anonymous Callbacks in SharePoint JSOM

Many asynchronous methods in SharePoint JSOM accept anonymous callback functions to handle the result. For example:

SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function() {

  var context = new SP.ClientContext();
  
  var web = context.get_web();
  
  context.load(web);

  context.executeQueryAsync(function() {
    // callback function handling result
    console.log('Title: ' + web.get_title());
  });

});

Here the executeQueryAsync method takes an anonymous callback function to process the result of the asynchronous request. This callback prints the title property of the Web object after the load operation completes.

Example Code of Anonymous Callback

function getListItems(listTitle) {

  SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function() {

    var context = new SP.ClientContext();
    var list = context.get_web().get_lists().getByTitle(listTitle);

    var items = list.getItems(SP.CamlQuery.createAllItemsQuery());

    context.load(items);

    context.executeQueryAsync(function() {
      var enumerator = items.getEnumerator();
      while (enumerator.moveNext()) {
        var item = enumerator.get_current();
        console.log(item.get_item('Title'));  
      }
    });

  });

}

This example uses an anonymous callback function to process and print out list items after the asynchronous call completes.

Declared Callback Functions

What are Declared Functions

Declared functions in JavaScript are function declarations that bind the function to an identifier name. Unlike anonymous functions, declared functions have an explicit name property.

function myFunction() {
  // function body 
}

This syntax declares a named function that can be called later by this identifier name. myFunction is now a callable property accessible in the current scope.

Using Declared Callbacks in SharePoint JSOM

Similar to anonymous callbacks, declared callback functions can also be passed to handle async results:

SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function() {

  var context = new SP.ClientContext();
  
  // Declare callback  
  function logTitle(sender, args) {
    console.log('Title: ' + web.get_title());
  }

  var web = context.get_web();
  
  context.load(web);

  context.executeQueryAsync(logTitle);

});  

The logTitle function is declared first, then passed by reference to executeQueryAsync. When the async call finishes, logTitle will run with the result parameters.

Example Code of Declared Callback

function getListItems(listTitle) {

  SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function() {

    var context = new SP.ClientContext();
    var list = context.get_web().get_lists().getByTitle(listTitle);  

    var items = list.getItems(SP.CamlQuery.createAllItemsQuery());

    context.load(items);

    context.executeQueryAsync(onQuerySucceeded);

  });
  
  // Declared callback function
  function onQuerySucceeded(sender, args) {

    var enumerator = items.getEnumerator();

    while (enumerator.moveNext()) {
      var item = enumerator.get_current();
      console.log(item.get_item('Title'));
    }

  }

}

Here onQuerySucceeded is a callable declared function passed to the async method. This encapsulates the callback logic for reusability.

Comparison of Approaches

Syntax

Anonymous functions provide lightweight inline syntax but lack a named identifier. Declared callbacks require more lines of code but encapsulate logic into reusable named functions.

Maintainability

Declared callback functions are easier to maintain as they abstract code into separate blocks that can be called by name. Debugging and editing is simpler compared to large anonymous functions.

Performance

There is generally no major performance difference between anonymous and declared callbacks. Declared functions may avoid duplicate code blocks if reused, providing minor optimization.

Recommended Best Practices

For simple single-use callbacks, anonymous functions are fine and reduce overall lines of code. However for more complex callbacks required across an application, declared callback functions are preferred.

Declared callbacks make the asynchronous flow easier to follow, avoid convoluted nested callbacks, and provide reusable abstraction.

FAQs

Can I mix anonymous and declared callbacks?

Yes, commonly simple one-off async calls would use inline anonymous callbacks, while complex logic is encapsulated into declared callback functions.

Are async/await promises better than callbacks?

Async/await provides an alternative approach to callbacks for handling async logic. Callbacks can create callback hell, while async/await uses standard synchronous-style code. However callbacks are still in widespread use with JSOM currently.

Leave a Reply

Your email address will not be published. Required fields are marked *