1

I have some API (LoadFileApi.load) for load file that fires callback on complete. There is common logic (prepare) and two different ways of processing (fired by click handlers) that are triggered upon prepare. I wonder, how to make it in clear and convenient, JS way?

function loadFile (onCompleteFileLoad) {
    LoadFileApi.load({
        url: 'url', 
      onComplete: filePreparing
    });
  }

function fileProcessing1() {

}

function fileProcessing2() {

}

// common logic
function filePreparing(file) {
   // prepare
   ...
   // after prepare I need to run file processing routine corresponding to each handler 
}

function clickHandlerA() {
    loadFile(filePreparing);

  // needs to trigger fileProcessing1
}

function clickHandlerB() {
    loadFile(filePreparing);

  // needs to trigger fileProcessing2
}

Simple decision is to declare shared variable and set it in each handler before file load.

function filePreparing(file) {
   // prepare
   ...
   if (processingMethod == 1) {
      fileProcessing1();
    } else {
      fileProcessing2();
    }

}

function clickHandlerA() {
    processingMethod = 1;
    loadFile(filePreparing);

}

function clickHandlerB() {
    processingMethod = 2;
    loadFile(filePreparing);

}

var processingMethod;

But it seems to me that more elegant JS way should exists... It would be great if there is no conditional choosing of processing function in PREPARE. It should be passed as parameter somehow...

Andrey Khataev
  • 1,303
  • 6
  • 20
  • 46

1 Answers1

0

I believe you want something similar to the answer to this question - JavaScript: Passing parameters to a callback function

Using the pattern described in the answer in the link above you will see that you can simply pass in parameters into your callback generically.

something like:

function clickHandlerB() {
    loadFile(filePreparing, fileProcessing1);

}

instead of passing a string flag to indicate which function to call just pass the function itself. The filePreparing function's signature will need to be updated to include the callback function

function filePreparing(file, callback)
Community
  • 1
  • 1
splay
  • 327
  • 2
  • 12
  • The problem is that API function is external one and has fixed signature with one parameter. So I see only thissolution https://jsfiddle.net/pn3xaLrb/ – Andrey Khataev Sep 24 '16 at 08:00