How to create callback in custom function using jquery - javascript

I would like to create a custom callback function for a custom function and pass callback as a parameter.
function customFunction(a, b, callback) {
// Some code
}
customFunction("val1", "val2", function(){
//Code to execute after callback
});

You're almost there...
function customFunction(a, b, callback) {
// Some code
if (typeof callback === 'function') {
callback();
}
}
customFunction("val1", "val2", function(){
//Code to execute after callback
});

The solution of Coulson is good. To show it more clearly we can add the timeout function as follow:
function customFunction(a, b, callback) {
setTimeout(function(){
console.log("original function");
callback();
},1000);
}
$(document).ready(function() {
$('#test').click(function() {
customFunction("val1", "val2",function(){
console.log("callback function");
});
});
});
Following is the link for check - https://jsfiddle.net/y0ch9exw/

Related

Javascript callback function not being fired

Apparently, the callback function is not being fired after the firstFunction().
What could be going wrong?
function callback () {
console.log("this is the callback function");
}
function firstFunction () {
console.log("this is the first function");
}
firstFunction(function () {
callback();
});
Is there any way to fix this?
As Ibrahim said, you have to call the callback if you want it to be called :)
e.g:
function callback(){
console.log("this is the callback function");
}
function firstFunction (cb){
console.log("this is the first function");
cb();
}
firstFunction(function () {
callback();
});
or inovke the function directly in the arg:
firstFunction(function () {
callback();
}());
EDIT:
Too late. Sorry. Anyway maybe you will find the second approach helpful.
Pass the second function as parameter
function callback() {
console.log("this is the callback function...");
}
function firstFunction(callbackFnc) {
console.log("this is the first function");
callbackFnc()
}
firstFunction(callback)
In the 'firstFunction' definition it doesn't expect a callback function.
When you invoke 'firstFunction' you are passing a function so maybe you need to change the definition a little bit. Something like...
function firstFunction(cb){ //now is expecting a callback function as parameter
console.log("something");
cb(); //calls the callback function!
}
Try it and check the other definitions too!
Hope it help!

jQuery with Callback and Complete

So I want to use a callback function within .fadeOut() after it complete's the animation. I can do this successfully using the following, no problem. Works just like I want (The HTML and CSS are just a single black square div)
function fadeOutThing(speed, callback) {
$('div').parent().fadeOut(speed, function() {
if (typeof callback === "function") {
callback();
}
});
}
function OtherThing() {
console.log("hello");
}
fadeOutThing(5000, OtherThing);
What I really want is for that callback function have its own argument, which could be another callback function, like the following. The problem is that when I do this, the log will display before the animation is complete: Here's the fiddle
function fadeOutThing(speed, callback) {
$('div').parent().fadeOut(speed, function() {
if (typeof callback === "function") {
callback();
}
});
}
function OtherThing(stuff) {
console.log("hello" + stuff); //This displays too soon!
}
fadeOutThing(5000, OtherThing(' stuffsss'));
Why is this happening? What am I not understanding?
The issue is because you call OtherThing() immediately on load of the page. This means you're giving the result of the OtherThing() function as the callback parameter, not the reference to the function.
To do what you require you can provide an anonymous function to the callback which wraps your OtherThing() call:
fadeOutThing(5000, function() {
OtherThing(' stuffsss'));
});
Bind the argument instead of calling the function as follows:
fadeOutThing(5000, OtherThing.bind(this,' stuffsss'));
Your are using/calling function in attribute so instead of function declaration you send its return in this case is no return so:
fadeOutThing(5000, OtherThing(' stuffsss'));
equals
fadeOutThing(5000, notDeclaredNothing); //undefined variable
To send function declaration and set paramaters you could do for example third paramater:
function fadeOutThing(speed, callback,attrs) {
$('div').parent().fadeOut(speed, function() {
if (typeof callback === "function") {
callback(attrs); //use with attributes
}
});
}
usage:
fadeOutThing(5000, OtherThing,'stuffsss');
Or second option is to use bind - bind creates new function with given this and given attributes:
fadeOutThing(5000, OtherThing.bind(this,'stuffsss'));
This in global scope is window object.

Test in which function a callback is executed

I'm trying to test in which function this callback function in executed. It should return a boolean value.
I hope you know what I mean.
Here the code example:
function test(par, callback) {
// ...
if (typeof callback == 'function') { // make sure the callback is a function
callback.call(this);
}
}
test("par", function() {
console.log("Test if in function test: " + "<if this is in function test>");
});
Is this similar to instanceof?
There's a non-standard way of doing it since the removal of arguments.caller
function test(par, callback) {
// ...
if (typeof callback == 'function') { // make sure the callback is a function
callback.call(this);
}
}
test("par", function cb() {
var isTestCaller = cb.caller === test;
console.log("Test if in function test: " + isTestCaller);
});
Another possible way doing it through error stacks (still non-standard):
var checkCaller = function(fnName) {
var e = new Error();
var caller = e.stack.split('\n')[2].trim().split(' ')[1];
return caller === fnName;
}
function wrapper(){
console.log(checkCaller('wrapper'));
}
wrapper();

Implement a callback function inside a function

Say I have a function like the following.
loadXML('Method', requestString, function(callback){
// The function as a callback parameter to loadXML goes here.
// Here I am calling the callback function like this
if(callback != null){
callback();
}
});
But I want to define this callback function inside the loadXML function. So can I do this as following?
loadXML('Method', requestString, function(callback){
// The function as a callback parameter to loadXML goes here.
// Here I have to call the callback function like this, (do I?) which is a
// callback parameter to callback function of loadXML
callback = function(){
// The callback function implementation goes here
}
});
Maybe this could help you to understand the nested callbacks mechanism:
var loadXML;
var outerCB;
var innerCB;
loadXML = function(method, requestString, cb) {
// pass the innerCB implementation as argument to the outer cb
if('undefined' !== typeof innerCB) {
cb(innerCB);
} else {
// in case innerCB would not be defined
cb(function() {
console.log('hi from anonymous cb')
});
}
};
innerCB = function() {
console.log('hi from innerCB cb!')
};
outerCB = function(callback) {
if('undefined' !== typeof callback) {
callback(); // innerCB();
} else {
console.log('no cb passed, do something else')
}
}
loadXML('Method', 'abcd', outerCB) // hi from innerCB cb!

passing arguments to callback

How can I pass arguments to a callback function in this specific scenario.
I have a function that gets an object with callbacks like this
function doSomething({ callbackSuccess : myFunction, callbackError : myOtherFunction})
how can I pass arguments to myFunction or to myOtherFunction?
Like, if myOtherFunction gets a msg parameter like this
function myOtherFunction(msg) {
alert(msg);
}
Thanks in advance
Just like you pass them to any other function:
function doSomething(callbacks) {
callbacks.callbackSuccess('foo', 'bar');
}
If you mean you want to pass them "at the time of passing them into doSomething":
doSomething({ callbackSuccess : function () { myFunction('foo'); }, ... });
Simplest of all:
function dosomething(callback) {
//some code-poetry;
callback(1, 2, 3); //the callback is back!!!
}
function foo(a, b, c) {//this will be my callback
alert("I got some parameters")
}
dosomething(foo); //the function call
Best explanation for a callback function:Check this
A simple defination would be:the callback function is called at a certain point in the future when some code or a function completes execution.
Try this -
// function def
function doSomething(a) {
}
// calling function
doSomething({
callbackSuccess : function() {
myFunction(msg);
},
callbackError : myOtherFunction
});

Categories