-1

can anyone explain line by line, I don't get how this call back and prototype works especially the function(callback) in js file

user.getUsers(function (theUsers) {
     $('#users-table-wrapper').html(user.getATable(theUsers));
});

this part in HTML

Js File

function User () {

}
User.prototype.getUsers = function (callback) {
    $.ajax({
        url: 'posting.php',
        data: {
            request:'get-users'
        },
        type:'post',
        dataType: 'json',
        success: function(users){
//            callback(users);
            if (callback) { callback(users); }
        }
    });
}

Here is my index.html

theUser is not declared but still works. when I type funcion (theUser) as far as I know theUser is a argument or a parameter. It has to be declared somewhere.

It seems it is neither of them.... how does this work?

<!DOCTYPE html>
<html>
<head>
    <title>Users</title>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script src="User.js"></script>
    <script>
        $(function () {
            var user = new User();
            user.getUsers(function (theUsers) {
                $('#users-table-wrapper').html(user.getATable(theUsers));
            });
        });   
    </script>
</head>
<body>
    <div class='main-wrapper'>
        <h3>Users</h3>
       <div id="users-table-wrapper">
       </div>
    </div>    
</body>
</html>
1
  • What do you not understand about the callback? it's a function stored in a variable that gets executed after an event (the ajax success) happens. As far as theUsers, that's a parameter that is being passed to the previously mentioned callback. Commented Sep 18, 2013 at 19:23

2 Answers 2

1

theUsers is a parameter to the anonymous function you provide as a callback:

function (theUsers) {
 $('#users-table-wrapper').html(user.getATable(theUsers));
});

In the success method of User.getUsers, you'll see it works like this:

success: function(users){
            if (callback) { callback(users); }
        }

Thus, if the AJAX call succeeds, and a callback is defined, the users parameter containing the data successfully retrieved is passed as the first argument to the callback function. Since the first argument is named theUsers in your anonymous callback definition, that's how it appears inside the method, making itself available for user.getATable(theUsers).

Sign up to request clarification or add additional context in comments.

Comments

0

theUser is a named argument to your function.

When calling the function, it gets the value of the first parameter passed.
You're calling the function here:

callback(users); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.