How to return value from anonymous function in js
2 answers
One thing you should know that you are working here with asynchronous actions. Let the numeric strings be in execution order (n means some large number much later)
1] $(document).on("click", '.delete-component', function(e) {
n+1] return 4;
});
2] console.log('here');
What you did was hooked up to a listener. For now, no click will happen - it will happen when someone clicks. This way you will access it after clicking. You can do two things:
- Declare var in the scope above.
- Direct value for callback
1) Example 1
var myValue = 0;
$(document).on("click", '.delete-component', function(e) {
myValue = 4;
});
function abc() {
console.log('myValue is equal to ' + myValue);
}
// if that line happen before clicking, value will be still 0
execture somewhen abc();
2) Example 2
$(document).on("click", '.delete-component', function(e) {
doSomethingWithValue(4);
});
function doSomethingWithValue() {
console.log('myValue is equal to ' + myValue);
}
You can also do some research on $ watch, especially Angular works a lot for you here.
+1
source to share
You need to specify what to do when the function or asyn operation has been reached, so usually returning when using callbacks is just another callback ...
function aux(param1, callback){
// do whatever...
$(document).on("click", param1, function(e) {
// return 4;
callback(4);
});
}
and you will use the code in yourself like this:
// your context..
// operations 1.. 2..
aux('.delete-component', function(theReturnedValue){
console.log(theReturnedValue); // 4
});
This is how callbacks return values ββto the outer scope.
+1
source to share