3

I'm building on my Three.js project and have been struggling for some time on how i could divide two functions into separate files

I have my Main.js(React Class Component) file that contains 200> rows of code and two of these functions that i would like to separate are:

startAnimationLoop()

  startAnimationLoop = () => {
    const tableBoard = this.scene.getObjectByName('tableSurface');
    tableBoard.rotation.y += this.title.RotationSpeed;

    this.renderer.render(this.scene, this.camera);
    this.requestID = window.requestAnimationFrame(this.startAnimationLoop);
  };

userGUI() ('dat.gui' Controller)

  userGUI = () => {
    const getTableSurface = this.scene.getObjectByName('tableSurface');

    this.gui = new dat.GUI();
    const controls = function() {
    this.RotationSpeed = 0.00;
  }
    this.title = new controls();
    this.gui.add(this.title, 'RotationSpeed', 0.0, 0.025);
  }

I call these functions inside the componentDidMount()

componentDidMount() {
    this.sceneSetup();
    addLights({ scene: this.scene });
    addFloor({ scene: this.scene })
    this.userGUI();
    this.startAnimationLoop();
    window.addEventListener("resize", this.handleWindowResize);
  }

I've been struggling with it for quite some time and any suggestions on how i could proceed with this process would be much appreciated.

Arasto
  • 471
  • 6
  • 25
  • so import and export, but since you are using them as part of the component with `this` it makes it a bit more complicated with binding. – epascarello Sep 17 '19 at 12:22
  • That's the part i'm struggling to figure out myself. – Arasto Sep 17 '19 at 12:25
  • To me it seems weird you are pulling it out in the first place. – epascarello Sep 17 '19 at 12:26
  • These functions will eventually be over 100 lines each, therefor i though that the best practice would be to separate them into another file. Maybe the right way to go is to write minor functions that i import into these major ones? – Arasto Sep 17 '19 at 12:30

1 Answers1

5

Personally I would not break it out, but if you want too, you need to export and import the methods. You also need to make sure you are calling it with the proper scope of this.

So make the file export the function

export const startAnimationLoop = () => {
  /* The Code
}

And your react component

import { startAnimationLoop } from './path/startAnimationLoop'

and when you call it

startAnimationLoop.call(this)

Or you can set it up in constructor with bind, and inside componentDidMount, you would use this.startAnimationLoop()

constructor(props) {
  super(props);
  this.startAnimationLoop = startAnimationLoop.bind(this);
}
epascarello
  • 204,599
  • 20
  • 195
  • 236