Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

javascript - Create a function to be called multiple times in multiple methods

Hello and happy new year everyone! I need a hand with a procedure that I repeat several times in multiple methods, please. I'll write you an example in short:

method1() {
  //I DO THINGS

  const controlArray = []; 
  this.daySelected.forEach((element) => {
    
    const tStart = element.time.map((t) => t.startIsGreater); 

    if (tStart.includes(true)) {
      
      controlArray.push(tStart); 
      this.setNewEventInfoRequired(false); 
      this.setAlertWarning(true); 
    }
  });
},

method2() {
  //I DO OTHER THINGS DIFFERENT FROM THE FIRST METHOD

  const controlArray = []; 
  this.daySelected.forEach((element) => {
    

    const tStart = element.time.map((t) => t.startIsGreater); 

    if (tStart.includes(true)) {
      controlArray.push(tStart); 
      this.setNewEventInfoRequired(false); 
      this.setAlertWarning(true); 
    }
  });
},
 // and then I repeat the same with other methods (methodFoo, methodBar, etc...)

Everything I write from const controlArray to the end, I repeat the same in multiple methods, so how do I put all that piece of code in one function and just call that function in the methods?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Just put that common code in one method then call it in every method:

runCommonFunc(){ // give it a significative name
     const controlArray = []; 
  this.daySelected.forEach((element) => {
    

    const tStart = element.time.map((t) => t.startIsGreater); 

    if (tStart.includes(true)) {
      controlArray.push(tStart); 
      this.setNewEventInfoRequired(false); 
      this.setAlertWarning(true); 
    }
  });
},

method1(){
//I do things
this.runCommonFunc()
},

method21(){
//I do things
this.runCommonFunc()
}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...