简体   繁体   English

Javascript,从回调返回值

[英]Javascript, returning value from a callback

I have 3 functions in javascript: 我在javascript中有3个功能:

function A(){
     B(data);
}

function B(data){
    element.on('click',function(){
         C(data);
    });
}

function C(data){
    //Process data
}

Function C does all data processing, but the data needs to be passed only on the click event, which I have defined in B. So, I need to pass data to B too, to ensure that C gets it. 函数C进行所有数据处理,但是只需要在我在B中定义的click事件上传递数据。因此,我也需要将数据传递给B,以确保C能够获取它。 Here, A is my main program and I'd rather not define the click event there. 在这里,A是我的主程序,我不想在那里定义click事件。 Is there any other way to pass data directly to C from A? 还有其他方法可以将数据从A直接传递到C吗?

Is there any other way to pass data directly to C from A? 还有其他方法可以将数据从A直接传递到C吗?

You will need to pass the call of C with th data to B for that: 为此,您需要将带有数据的C调用传递给B:

function A(){
    B(function(){
         C(data);
    });
}

function B(data){
    element.on('click', callback);
}

function C(data){
    //Process data
}

It would work the same way as the code you already have, but has decoupled B from C. 它的工作方式与您已有的代码相同,但是已将B与C分离。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM