I have the following jQuery function:
function deleteHype(){
FB.api('/me/launchhype:hype', function(response) {
$.each(response.data, function(i, obj){
if (obj.data.launch.url == '<?php the_permalink(); ?>') {
var delete_launch_id = parentObj=obj.id;
}
});
});
}
alert(delete_launch_id);
Lets say in the IF statement the var “delete_launch_id” is “X”. Well if I try to do the alert “delete_launch_id” outside the function it is “undefined”. I want it to give me back “X” (the hypothetically value that was set).
How can I do this? I’m lost and can’t seem to find a similar example.
By popular demand, here’s a more in depth look at why the variable “delete_launch_id” isn’t available at the point where it’s accessed by the “alert” function.
There’s a couple things going on.
First, the FB.api function is most likely an asynchronous AJAX call. JavaScript isn’t truly asynchronous (yet), but in this case, it effectively behaves so. What that means is that when asynchronous code executes, code after it will continue executing while the async code waits for a response. So, there’s a good chance that if you call “deleteHype”, and then “alert” immediately following it, FB.api response won’t have returned by the time “alert” is called. And as such, anything set within that async code won’t be available yet.
The second issue is that JavaScript has “functional scope.” What that means, in practice, is that a variable defined inside a function is only available inside that function. It only has “scope” within that function. Consider the following code:
“foo” changed because it had scope outside the function, so the function can access it.
“bar” however, only has scope inside that function and doesn’t exist anywhere else.
In the original example, “delete_launch_id” is declared inside several functions, actually, so it is not available anywhere else.
My first answer addresses these issues by passing a function into the “deleteType” function as a “callback” that will be called only when the async code is finished and returns. That handles issue #1. The callback function then has “delete_launch_id” passed to it, which makes it available. The format I gave may seem a little weird:
What’s going on here is that we’re actually passing a function as a variable. It’s an “anonymous” function (no name). So deleteType treats is like a variable (because it is), and can call it, because it’s a function, and the code inside it will execute when it’s called. It’s a really handy pattern.
I hope that helps a bit. This is confusing stuff at first.