Converting threejs' IIFE functions to es6?

后端 未结 2 1417
滥情空心
滥情空心 2021-01-24 15:46

I\'m trying to break my threejs project into smaller modules and I\'m having a tough time. Take this function for example:

var updateCamera = (function() {
    v         


        
相关标签:
2条回答
  • 2021-01-24 16:32

    Instead of assigning to the (global?) updateCamera variable, use a (default) export. You can drop the whole IIFE, as every module has its own scope; so euler will be inaccessible and static even in the module top level.

    You also might want to explicitly declare the dependency on Three.js instead of relying on globals.

    // updateCamera.js
    import { Euler } from 'three';
    
    var euler = new THREE.Euler( 0, 0, 0, 'YXZ' );
    
    export default function updateCamera(camera, motion) {
        euler.x = motion.rotation.x;
        euler.y = motion.rotation.y;
        camera.quaternion.setFromEuler( euler );
    
        camera.position.copy( motion.position );
        camera.position.y += 10.0;
    }
    

    Then you can use it in other modules by doing

    // main.js
    import updateCamera from './updateCamera';
    
    …
    updateCamer(camera, motion);
    

    Notice that camera and motion should be passed as arguments here. Again, don't depend on globals; if you don't want to pass them around everywhere you might also create a module that exports them and from which you could do

    import {camera, motion} from './globals';
    
    0 讨论(0)
  • 2021-01-24 16:39

    Lets say I wanted to break this updateCamera function into its own file and import it. I'm a bit confused on how to since it's self executing. Can anyone give me a hand?

    Well the only point of the IIFE in this case is to make euler "private". Because each file gives you its own context in Node, you can do this without the IIFE easily

    // Camera.js
    
    import { Euler } from 'three'
    
    const euler = new Euler( 0, 0, 0, 'YXZ' )
    
    export const updateCamera = (camera, motion) => {
      euler.x = motion.rotation.x
      euler.y = motion.rotation.y
      camera.quaternion.setFromEuler( euler )
      camera.position.copy( motion.position )
      camera.position.y += 10.0
    }
    

    Using it is like this

    import { updateCamera } from './Camera'
    
    // const camera = ..., motion = ...
    
    updateCamera(camera, motion)
    
    0 讨论(0)
提交回复
热议问题