[英]How does this javascript callback function work?
can anyone explain line by line, I don't get how this call back and prototype works especially the function(callback) in js file 任何人都可以逐行解释,我不知道此回调和原型如何工作,尤其是js文件中的函数(回调)
user.getUsers(function (theUsers) {
$('#users-table-wrapper').html(user.getATable(theUsers));
});
this part in HTML 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 这是我的index.html
theUser is not declared but still works. 没有声明theUser,但仍然可以使用。 when I type funcion (theUser) as far as I know theUser is a argument or a parameter. 据我所知,当我输入funcion(theUser)时,User是一个参数或参数。 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: theUsers
是您作为回调提供的匿名函数的参数:
function (theUsers) {
$('#users-table-wrapper').html(user.getATable(theUsers));
});
In the success method of User.getUsers
, you'll see it works like this: 在User.getUsers
的成功方法中,您将看到它的工作方式如下:
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. 因此,如果AJAX调用成功,并且定义了回调,则包含成功检索到的数据的users
参数将作为第一个参数传递给回调函数。 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)
. 由于第一个参数在您的匿名回调定义中被命名为theUsers
,因此它就出现在方法中,从而可用于user.getATable(theUsers)
。
theUser
is a named argument to your function. theUser
是函数的命名参数。
When calling the function, it gets the value of the first parameter passed. 调用该函数时,它将获取传递的第一个参数的值。
You're calling the function here: 您在这里调用该函数:
callback(users);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.