How to return value from anonymous function in js
anonymous-function, javascript
Solution
One thing you have to be aware that you work here with asynchronous actions. Let's number lines in order of exaction (n means some high number far far later)
1] $(document).on("click", '.delete-component', function(e) {
n+1] return 4;
});
2] console.log('here');
What you did was attached listener to click. Click won't happen at the moment - it will happen when someone clicks. Therefore you will have access to it after click happens. You can do two things:
- Declare var in scope above.
- Forward value to 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 investigate $watch, especially Angular does here a lot work for you.
Problem
I would like to return value from anonymous function. How can I assign returned value to $id variable in below code ? ``` $(document).on("click", '.delete-component', function(e) { return 4; }); //$id in this scope should be equal 4 ```