Implement a callback function inside a function - javascript

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!

Related

Anonymous function argument

I have a section in my code that looks like this
var locationDefer = $.Deferred();
if (saSel.Company === -1) {
database.getAllLocations().then(function (result) {
var locations = JSON.parse(result.d);
locationDefer.resolve(locations);
});
} else {
database.getLocationsForCompany(saSel.Company).then(function (result) {
var locations = JSON.parse(result.d);
locationDefer.resolve(locations);
});
}
However, since it is basically the same thing twice, just with a different ajax call - is there any way to either have the anonymous function part
function (result) {
var locations = JSON.parse(result.d);
locationDefer.resolve(locations);
})
declared as a real function and then just called in the .then() clause, or can I somehow provide the to-be-called-function of the database object?
For the latter, I had something in my mind that could look like this, but I have no clue how to do the last line.
if(saSel.Company === -1) {
fun = 'getAllLocations';
arg = null;
} else {
fun = 'getLocationsForCompany';
arg = saSel.Company;
}
// database.fun(arg).then(function (result) {...});
You can define a function and pass its reference as success callback handler
//Define the function handler
function resultHandler(result) {
var locations = JSON.parse(result.d);
locationDefer.resolve(locations);
}
if (saSel.Company === -1) {
fun = 'getAllLocations';
arg = null;
} else {
fun = 'getLocationsForCompany';
arg = saSel.Company;
}
//Invoke the method using Bracket notation
//And, pass the success handler as reference
database[fun](arg).then(resultHandler);
Additionally, as getLocationsForCompany() and getAllLocations() returns a promise, you shouldn't use $.Deferred() directly return Promise
return database[fun](arg);

Use a Variable From Expression In It's Callback

A lot of the stuff I find when searching for this starts talking about Ajax so I'm not even sure what I'm trying todo is possible.
I have the following JavaScript:
function getFruit(callback) {
var result;
result = "banana";
// Make sure the callback is a function​
if (typeof callback === "function") {
// Call it, since we have confirmed it is callable​
callback();
}
return result;
}
getFruit(function(){
console.log(getFruit());
}
I simply want to pass the current value of result to the callback function so that it can be used there.
Please advise.
You need to pass the result as parameter to the callback function.
function getFruit(callback) {
var result = "banana";
if (typeof callback === "function") {
callback(result);
}
}
getFruit(function(parameter) {
console.log(parameter);
})
One way is to pass it as callback parameter:
function getFruit(callback) {
var result;
result = "banana";
// Make sure the callback is a function​
if (typeof callback === "function") {
// Call it, since we have confirmed it is callable​
callback(result);
}
return result;
}
getFruit(function(result){
alert(result);
});
Other way (since it's not async function) is to create global variable and than use it:
var result;
function getFruit(callback) {
result = "banana";
// Make sure the callback is a function​
if (typeof callback === "function") {
// Call it, since we have confirmed it is callable​
callback();
}
}
getFruit(function(){
alert(result);
});
You can do something like this:
function getFruit(callback) {
var result;
result = "banana";
// Make sure the callback is a function​
if (typeof callback === "function") {
// Call it, since we have confirmed it is callable​
callback(result);
}
}
getFruit(function(response){
console.log(response);
})

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();

How to create callback in custom function using jquery

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/

How can I write a function accepting callBack function and run it in a 'safe' way?

I want to write such a function:
function doGoodJob(someId, callBackfunction){
// some stuff with someId
// todo: RUN callBackFunction here
}
They say eval is 'dangerous' in terms of code injection.
so, what is the best practice to write a JavaScript function that accepts a call-back function and runs it securely?
Is your callback a string or an actual function ?
If its a function..
function doGoodJob(someId,callbackFunction)
{
callbackFunction();
}
doGoodJob(1,function(){alert('callback');});
If its a string you can use the Function constructor.
function doGoodJob(someId,callbackFunction)
{
var func = new Function(callbackFunction)
func();
}
doGoodJob(1,"alert('test');");
Or test for both..
function doGoodJob(someId,callbackFunction)
{
var func = (typeof callbackFunction == 'function') ?
callbackFunction : new Function(callbackFunction);
func();
}
doGoodJob(1,function(){alert('callback');});
doGoodJob(1,"alert('test');");
This should work:
function doGoodJob(simeOd, callBackFunction){
/** Do stuff **/
callBackFunction();
}
quick fiddle: http://jsfiddle.net/pS67X/
though late to this topic, just wanted to adde some thing.
Above solution works for alert or passing function as argument, but not in the below case.
doGoodJob(1, "someCallbackFunction");
function someCallBackFunction() {
alert("im called");
}
instead if use eval(callbackFunction) like below
function doGoodJob(someId,callbackFunction) {
var func = (typeof callbackFunction == 'function') ?
callbackFunction : eval(callbackFunction);
func();
}
doGoodJob(1,someCallBackFunction);
doGoodJob(1,"someCallBackFunction");
Callback function means function pass as an argument like we pass variable.
When calling the callback function, we could use it like below:
<script>
function callbackExample(arg1, callback){
alert(arg1);
var x = 10, y = 20;
if (callback && typeof(callback) === "function") {
callback(x+y);
}
}
callbackExample("test", function(res){
alert("This is the callback function..." + res);
});
</script>

Categories