What is this Javascript code? Explain
This is a snippet from the Facebook Developers site.
<div id="info"></div&g开发者_开发知识库t;
<script>
var
info = document.getElementById('info'),
update = function(response) {
if (!response.session) {
info.innerHTML = '<em>You must login using the controls at the top.</em>';
return;
}
FB.api(
{
method: 'fql.query',
query: 'SELECT name, pic_square FROM user WHERE uid=' + response.session.uid
},
function(response) {
info.innerHTML = (
'<img src="' + response[0].pic_square + '"> ' +
response[0].name
);
}
);
};
// update on login, logout, and once on page load
FB.Event.subscribe('auth.login', update);
FB.Event.subscribe('auth.logout', update);
FB.getLoginStatus(update);
</script>
Above, can you please tell me what is the update variable, its type and how works, where does the assignment ends and who calls this function?
Secondly, what's the first argument to the FB.api call? What type of object is it? And I believe the second one is a callback function right?
The update is a callback to that function. It will get executed based on what "Subscribe" does. The data being passed in is JSON. Its a plain text data representation language used to send data.
It is not SOAP-ish, its JSON. Used to pass data back and forth in javascript. It is very lightweight. http://en.wikipedia.org/wiki/JSON
Its passing an object into FB.api that has two string members: method, and query.
update is a function. In JavaScript you can define a function either by
var update = function () {
// body
};
or by
function update() {
// body
}
And as functions are first-class citizens, you can pass them as an argument, as in the FB.Event.subscribe call.
You can also define the functions inline using an anonymous function:
FB.Event.subscribe('auth.login', function () {
// body
});
The first parameter of the FB.api call is an object (a collection of key-value pairs) with two keys: 'method' and 'query' which have strings as their values.
You can read more about the JavaScript object notation (JSON) here: http://json.org/
The first argument is just a string, looks like a namespaced soap-ish event name. The second is indeed a function, must be used as a callback of some kind.
精彩评论