admin管理员组文章数量:1287626
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-ponent', function(e) {
return 4;
});
//$id in this scope should be equal 4
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-ponent', function(e) {
return 4;
});
//$id in this scope should be equal 4
Share
Improve this question
edited Dec 2, 2014 at 13:21
Thomas Shelby
asked Dec 2, 2014 at 13:13
Thomas ShelbyThomas Shelby
1,3705 gold badges20 silver badges39 bronze badges
3
-
You cannot assign it to anything before the click has happened. No, you cannot
return
a value from an asynchronous callback. – Bergi Commented Dec 2, 2014 at 13:15 - Event callback will be called on click, but you can't assign its result. However you can make some assignments inside of it. – dfsq Commented Dec 2, 2014 at 13:16
- What are you going to do with the return value? – Sampath Liyanage Commented Dec 4, 2014 at 14:51
2 Answers
Reset to default 4You need to specify what to do when asyn function or operation is reached, so usually a return when using callbacks is another callback...
function aux(param1, callback){
// do whatever...
$(document).on("click", param1, function(e) {
// return 4;
callback(4);
});
}
and you would use it in you code as following:
// your context..
// operations 1.. 2..
aux('.delete-ponent', function(theReturnedValue){
console.log(theReturnedValue); // 4
});
This is how callbacks 'return' values to an outer scope.
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-ponent', 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-ponent', 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-ponent', 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.
本文标签: javascriptHow to return value from anonymous function in jsStack Overflow
版权声明:本文标题:javascript - How to return value from anonymous function in js - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741314964a2371860.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论