Wednesday 18 September 2013

How does this javascript callback function work?

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
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>

No comments:

Post a Comment