How to know that a callback function has fired? - javascript

How can I know that a callback event has fired? I have to perform an activity after the callback event has fired, should I put the code inside the callback function or is there some other way to know when the callback has fired? Even if I put the code of the activity after the statement making the javascript request I cant be sure that the code of the activity will be executed after the callback has fired?

You have to put it in the callback function. You can do this indirectly (e.g. the callback function calls another).

How can I know that a callback event has fired?
do something at the end of the callback. like calling the function that should be invoked after the callback.
I have to perform an activity after the callback event has fired, should I put the code inside the callback function or is there some other way to know when the callback has fired?
There is no other way to determine if a callback has been fired.
Even if I put the code of the activity after the statement making the javascript request I cant be sure that the code of the activity will be executed after the callback has fired?
by "javascript request" do you mean "ajax request". If so I would advise at doing it this way because it most probably will be fired before the callback. At most ajax requests are per definition asynchronous (Asynchronous JavaScript and XML = AJAX). And because of that the script won't wait for the response of the request to continue with itself. That is why you should use callbacks. Callbacks make sure that some code is called after something specified had happened.

How to know that a callback function
has fired?
You can simply put an alert in the callback function to know whether or not it has fired.
Code inside the callback function will fire anyway.

If you had a callback function like following:
setup(data, namespaces, eventHandler) {
$(this).resize(eventHandler);
});
You can pull your callback into another callback and take control before that function is called.
setup(data, namespaces, eventHandler) {
$(this).resize(() => {
console.log("calling eventHandler()")
eventHandler();
});
});

Related

What are callback function?

I ask a friend and ask what is (data, function(i,e) in this code and he said this is callback then i search the internet about callback and doesn't understand it. I read about this What are callback methods?what is callback in simpliest way ?
$.each(data, function(i,e){
console.log(e.id);
});
What is the use of (data, function(i,e) here?
$.ajax({
type: "GET",
url: pbxApi+"/confbridge_participants/conference_participants.json?cid="+circle,
dataType: "jsonp",
jsonpCallback: 'callback',
contentType: "application/javascript",
success: function(data) {
console.log(data);
}
});
A callback function is a function you specify to an existing function/method, to be invoked when an action is completed, requires additional processing, etc.
*Here's a little something for you to understand callbacks better:
Guy 1 to Guy 2: hey dude I wanna do something when a user clicks in there, call me back when that happens alright?
Guy 2 calls back Guy 1 when a user clicks here.*
A callback method which is called back.
Who calls it back at you ?
Your framework calls it back.
Why it calls it back ?
Because you ask for it to get called back because you want to do some processing when something happens.
Examples
You are doing some processing and don't know when it completes. You provide a callback , and you continue with some other work. Your call-back function will be called back to tell you that processing is finished and you can do something at your end now.
You want to know when some control fires some event so that you can do some processing. You provide a call-back function as event handler.
You are not happy with default processing done by framework and want to override that processing, you provide a call-back and framework calls it back to use your own processing.
So, in general : You ask a component/framework to call your provided method. You never call that provided method from your code, someone else calls it back.
A callback function is a function that is passed to another function as a parameter, and the callback function is called (or executed) inside the another Function.
Like this
(data, function(i,e)
We can pass functions around like variables and return them in functions and use them in other functions. When we pass a callback function as an argument to another function, we are only passing the function definition.
Note that the callback function is not executed immediately. It is “called back” at some specified point inside the containing function’s body. For more info Refer Here
Normally, JavaScript statements are executed line by line. However, with effects, the next line of code can be run even though the effect is not finished. This can create errors.
To prevent this, you can create a callback function.
A callback function is executed after the current effect is finished.
For e.g, this is a call back function:
$("button").click(function(){
$("p").hide("slow", function(){
alert("The paragraph is now hidden");
});
});
In this case the function hide will be executed before that alert which is precisely what we want.
On the other hand if you don't use call back function say this way:
$("button").click(function(){
$("p").hide(1000);
alert("The paragraph is now hidden");
});
In this case alert will be executed even before the function hide is executed. This is the typical use of callback function in Javascript.

What is difference between calling a function and callback function?

What is the difference between following snippets
// calling a function
function execute(){
}
function fn(){
asynchronousFunction(function(){
execute();
})
}
fn();
How the below snippet is different from above
// callback a function
function execute(){
}
function fn(done){
asynchronousFunction(function(){
done();
})
}
fn(execute);
In which way callback is different from calling a function directly? What are pros and cons of each approach?
If you call a function, it will execute immediately.
If you pass the function as an argument to another function, then some other code will call it later (at which point it will execute).
They aren't different approaches for doing the same thing. You use a callback when you are writing a function that needs to do something at some point, but when what that something is depends on something outside the function.
The classic example is addEventListener. For the sake of discussion, let's limit ourselves to click events. You have a standard function for making something happen when something is clicked. Lots of programs want something to happen when something is clicked, but that something can be almost anything.
In first case, your function fn() can see execute() and the parameter is optional, because anytime you call fn() will be called execute().
in second case, you made your function more "general" and you may customize your callback function
The first option presents fn as a simple function that starts some kind of asynchronous action and doesn't present any other information to the outside. If fn is something like uploadData, then you'd have a simple function that tries to upload it (and maybe display an error message if it fails, or a success message when it's done), but the caller can only start it and do nothing else.
The second option additionally allows the caller of fn to decide what should happen when fn completes. So if fn is uploadData, then the caller is able to also specify what should happen once the data has been uploaded (or if there has been an error).
Callbacks like these gives you a lot of flexibility. In your second example, you are able to say: "Do fn(), and do the asynchronous function, and if you have finished, then call done()." And the point is, you can decide what done() does, although you have no insight in the method that calls it.
Delivering functions as an argument, that are to be executed e.g. at the begin, at the end or at other events, is a fundamental principle. It is the basis for hooks, callbacks, promises, configuring of complex objects etc.

Execute a method whenever some method has finished executing completely

I've a javascript method defined as follows:
updtCrtEdtPage = function() {PrimeFaces.ab({source:'j_id_ev',formId:'j_id_es',process:'typeNewLOB_in lobIdForEdit j_id_ev',update:'createLOBFullPagePanel',oncomplete:function(xhr,status,args){prepareForCrtEdtFullPage();},params:arguments[0]});}
I want to execute certain method (afterComplete()) whenever this method has finished executing. (This method actually initiates an ajax request & appends the received HTML data on the DOM). So I want my afterComplete() method to be executed whenever ajax response has been received.
I cannot directly do like:
updtCrtEdtPage();
afterComplete();
as this would call the afterComplete() soon after ajax request is initiated & not completely finished executing yet.
Is there any JS/ jQuery way I could do that ?
You could pass afterComplete as a parameter so your function can call it when the ajax call is complete. Something like this...
updtCrtEdtPage = function(callback) {
PrimeFaces.ab({
source:'j_id_ev',
formId:'j_id_es',
process:'typeNewLOB_in lobIdForEdit j_id_ev',
update:'createLOBFullPagePanel',
oncomplete:function(xhr,status,args){
prepareForCrtEdtFullPage();
callback();
},
params:arguments[0]
});
}
updtCrtEdtPage(afterComplete);
Since you say you can't modify updtCrtEdtPage, but you can modify prepareForCrtEdtFullPage I'd suggest using a global variable to determine which callback function to call when the method is complete...
updtCrtEdtPageCallback = afterComplete;
and then in prepareForCrtEdtFullPage just add the last line...
updtCrtEdtPageCallback();
The first method is tidier, but the second will suffice for your particular situation.
your updtCrtEdtPage = function() has an oncomplete callback which is called when the ajax response has been received, add your afterComplete function in that callback and it will execute after the ajax request has been completed.
oncomplete:function(xhr,status,args){
prepareForCrtEdtFullPage();
afterComplete()
}

Javascript callback being fired before function is complete (no jQuery)

I have 2 javascript functions, the first being a function which loads ajax content (via another function), and a second which is a callback function. They look like:
function createReply(callBack){
ajaxPage('test.html', 'next-reply');
callBack();
}
function updateNext(){
document.getElementById('next-reply').id = "reply-item";
}
createReply(updateNext);
As you can see, I am calling the createReply() function and passing it the name of the callback function, in this case updateNext()
In the createReply() function, I am calling another function which loads content via ajax. When this function is complete, the callback is supposed to be executed. The callback changes the id of the div in which the ajax content is being loaded. This is where the problem is occuring
I am getting the error:
Uncaught TypeError: Cannot set property 'innerHTML' of null
Which is saying that it cannot change the content of the element with the id "next-reply" because it doesn't exist, and the reason it doesn't exist is because the callback function changes the id if that element. The intention is to have the callback fire after the ajax content has been loaded (ie; after the ajaxPage() function has been executed)
Can anyone see what the problem is? Is there a better way of implementing a callback function in plain javascript?
PS: no jQuery
As pointed out in the comments, this is due to the fact that AJAX calls happen asynchronously. The thread that createReply runs in continues to run before a response is returned from the server.
You'll need to re-factor ajaxPage to accept a reference to callback, and call it when the response is ready. Something like:
function createReply(callBack){
ajaxPage('test.html', 'next-reply', callBack);
}
Then, in ajaxPage:
function ajaxPage(url, id, callback){
//Do AJAX stuff
//When the response is returned:
if(callback) callback();
}
Right now you callback is executed right after the ajaxPage function. By right after I mean you do not wait for ajaxPage to return success. It is fired right after the ajax call goes out. It is very likely that it is not completed before your callback is fired.

How can I wait for a click event to complete

I add a click event handler to an element
$(".elem").click(function(){
$.post("page.php".function(){
//code1
})
})
And then I trigger a click event
$(".elem").click();
//code2
How can i make sure that code2 executes after code1 executes
(Ignoring WebWorkers) JavaScript runs on a single thread, so you can be sure that code2 will always execute after code1.
Unless your code1 does something asynchronous like an Ajax call or a setTimeout(), in which case the triggered click handler will complete, then code2 will execute, then (eventually) the callback from the Ajax call (or setTimeout(), or whatever) will run.
EDIT: For your updated question, code2 will always execute before code1, because as I said above an async Ajax callback will happen later (even if the Ajax response is very fast, it won't call the callback until the current JS finishes).
"How i make sure that code2 executes after code1 executes"
Using .click() with no params is a shortcut to .trigger("click"), but if you actually call .trigger() explicitly you can provide additional parameters that will be passed to the handler, which lets you do this:
$(".elem").click(function(e, callback) {
$.post("page.php".function(){
//code1
if (typeof callback === "function")
callback();
});
});
$(".elem").trigger("click", function() {
// code 2 here
});
That is, within the click handler test whether a function has been passed in the callback parameter and if so call it. This means when the event occurs "naturally" there will be no callback, but when you trigger it programmatically and pass a function then that function will be executed. (Note that the parameter you pass with .trigger() doesn't have to be a function, it can be any type of data and you can pass more than one parameter, but for this purpose we want a function. See the .trigger() doco for more info.)
Demo: http://jsfiddle.net/nnnnnn/ZbRJ7/1/
You can try writing this way:
$(".elem").live("click", function(){
//code1
})
// for newer jquery version from 1.9
$(".elem").on("click", function(){
//code1
})
And, your trigger will always execute as fired.
Wrap code2 in method and add it as a callback inside code1 so it will always get called after code1 executes
code2 = function(){/*code2*/};
$(".elem").click(function(){
//code1
code2();
})
Javascript execution is line by line. So whatever comes up, will be executed first. So adding the click code before the other method will work.
Plus if there is any async call, then take a flag which is set only when you get response.
var clicked = false;
$('#elem').click(function(){
// do some async process
clicked = true;
});
while (!clicked){ // do nothing }
// other function to be called
Or the second option will be, if using post method, set async = true in property.

Categories