Converting threejs' IIFE functions to es6?

后端 未结 2 1416
滥情空心
滥情空心 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';
    

提交回复
热议问题