To Add CallBack in JavaScript
Why we need callback when using URL to fetch data?
–When we pull data using url. It takes some time to load the Url .Hence the code where the data is required executes before the data is loaded. Thus, We need to add a callback to the java script function where data is loaded.
THE BASICS:-
function ftn1(callback) {
// ...
// Call the callback
callback('stuff', 'goes', 'here');
}
function ftn2(a, b, c) {
// I'm the callback
alert(a + " " + b + " " + c);
}
ftn1(ftn2);
ftn1(ftn2) will call ftn1 which will call ftn2, which will alert "stuff goes here".
NOTE:
It's very important to pass the function reference(ftn2).
Rather than calling the function and passing its result(ftn2()).
For example:-
Here we have two functions.
ShapeFtn() and Census_DataFtn()
We need to 1st load the shape file using the ‘ShapeUrl’ and once it is loaded Census_DataFtn() should execute,where
we are using the shape file from the ShapeFtn().
function ShapeFile(callback)
{
var xhr = createCORSRequest('GET', ShapeUrl);
xhr.send();
xhr.onload = function() { shape = xhr.responseText; }; xhr.onloadend = function() { shape = $.parseJSON(shape); callback(shape); }; } //Get Census data function Census_DataFtn(shape) { var xhr = createCORSRequest('GET', url); xhr.send(); xhr.onload = function() { census_data = xhr.responseText; }; xhr.onloadend = function() { census_data = $.parseJSON(census_data); geo=merge(census_data, shape); }; } } ShapeFile(Census_DataFtn);
Hence, calling the function ShapeFile(Census_DataFtn) which will call Census_DataFtn and will pass the shape value.
Best Open Source Business Intelligence Software Helical Insight is Here
A Business Intelligence Framework
Regards,
Devang Sharma
Helical It Solution
Subscribe
Login
0 Comments