0

I have 3 functions in javascript:

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. Here, A is my main program and I'd rather not define the click event there. Is there any other way to pass data directly to C from A?

4
  • So basically, you call A() which then calls B(). Then you wait for the click, and on click you execute C()? Commented Apr 4, 2014 at 12:38
  • 2
    What is wrong with the solution you have now? Commented Apr 4, 2014 at 12:40
  • Yup. I'm really new to Javascript and Im not sure if this is a proper way of doing stuff. Commented Apr 4, 2014 at 12:40
  • @putvande: The data differs each time A is called. But B does a lot of stuff, like creating div elements using d3. If I call it again, an entirely new set of elements are created. If I dont call it again, C gets the same old data over and over again, which is also not desirable. There are various workaround, but, just wanted to know if there were any methods in JS to simplify this. Commented Apr 4, 2014 at 12:43

1 Answer 1

1

Is there any other way to pass data directly to C from A?

You will need to pass the call of C with th data to B for that:

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.

Sign up to request clarification or add additional context in comments.

2 Comments

So, if C has a return value, where would this value get returned to? A or B?
Neither. Callbacks don't return anything, they pass their results on (also called continuation-passing-style). You might use C()s (synchronous) results in the anonymous function though

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.