Use a Variable From Expression In It's Callback - javascript

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

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

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!

executing function based on condition

I want to write something like this:
function MyFunction () { .... return SomeString; }
function SomeFunction () { ... return SomeOtherString; }
function SomeCode() {
var TheFunction;
if (SomeCondition) {
TheFunction = SomeFunction;
} else {
TheFunction = SomeCode;
}
var MyVar = TheFunction(); // bugs here
}
Basically, I'd like to execute a function after some condition has been evaluated so that variable MyVar contains contains the result of the function that has been called.
What am I missing to make this work?
Thanks.
If you are just talking about conditionally executing a function and storing the results...
var result;
if( condition ){
result = foo();
}else{
result = bar();
}
var myVar = result;
If you want to determine the function to call, but not call it until another time, use:
// define some functions
function foo(){ return "foo"; }
function bar(){ return "bar"; }
// define a condition
var condition = false;
// this will store the function we want to call
var functionToCall;
// evaluate
if( condition ){
functionToCall = foo; // assign, but don't call
}else{
functionToCall = bar; // ditto
}
// call the function we picked, and alert the results
alert( functionToCall() );
Callbacks can be very useful in JS...they basically tell the consumer to "call this when you think it's appropriate".
Here's an example of a callback passed to the jQuery ajax() method.
function mySuccessFunction( data ){
// here inside the callback we can do whatever we want
alert( data );
}
$.ajax( {
url: options.actionUrl,
type: "POST",
// here, we pass a callback function to be executed in a "success" case.
// It won't be called immediately; in fact, it might not be called at all
// if the operation fails.
success: mySuccessFunction
} );

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