Sookie J
Sookie J

Reputation: 893

A Callback Function for attr()

As far as I understand, callback is a function executed after its parent method is executed. But the method attr() in the code below doesn't seem to be executed first as it should be as its name 'callback'. Could you help me understand this code?

   $("button").click(function(){
        $("#w3s").attr("href", function(i, origValue){
            return origValue + "/jquery"; 
        });
    }); 

It seems that "function(i, origValue)" is executed ahead of "attr()".

Upvotes: 1

Views: 1116

Answers (1)

Pointy
Pointy

Reputation: 413712

A "callback" is not necessarily executed after the method into which it's passed. It's executed whenever the called method wants to execute it.

In this case, the implementation of .attr() calls the callback while it is operating. It iterates through the elements of the jQuery object and calls the callback once for each element. The last call to the callback will be finished before the call to .attr() returns.

The notion that callbacks are called after the original called method finishes probably stems from the fact that callbacks provide a way to deal with asynchronous situations. That doesn't have anything to do with the concept of a callback, however; instead, it's a way of taking advantage of the fact that callbacks are available in the language.

In this case, since there is no asynchronous funny business going on, why would the API involve a callback? The point of the callback in .attr() is to provide a way of making additional decisions or doing additional computation on a per-element basis. With the callback, your own code (the function you pass as the callback) can examine each original attribute value and interpret it however you want to do so. The code can decide to leave some elements alone while updating others, based on your own criteria. You still get to take advantage of the jQuery code performing the iteration for you, and you can focus on just the logic for examining and update the attribute values.

Upvotes: 2

Related Questions