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
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.
<!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>
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)
.
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.