Is it possible to translate the IIFE functions of threejs into ES6 format?

I'm currently facing a challenge in breaking down my threejs project into smaller modules. One specific function that I'm struggling with is the following:

var updateCamera = (function() {
    var euler = new THREE.Euler( 0, 0, 0, 'YXZ' );

    return function() {
        euler.x = motion.rotation.x;
        euler.y = motion.rotation.y;
        camera.quaternion.setFromEuler( euler );

        camera.position.copy( motion.position );
        camera.position.y += 10.0;
    };
})();

If I wanted to separate this updateCamera function into its own file and import it, I'm unsure of how to proceed due to it being self-executing. Can anyone provide assistance?

Answer №1

To improve the structure of your code, consider using a default export instead of assigning to the global variable updateCamera. You can remove the IIFE as each module has its own scope, making euler inaccessible and static even at the top level of the module.

It is also recommended to explicitly declare dependencies on Three.js rather than 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;
}

Now you can easily use this function in other modules by importing it like so:

// main.js
import updateCamera from './updateCamera';

…
updateCamer(camera, motion);

Remember to pass camera and motion as arguments when using the function. Avoid relying on global variables; if you prefer not to pass them around everywhere, consider creating a module that exports them for easier access.

import {camera, motion} from './globals';

Answer №2

Wanting to separate the updateCamera function into its own file and import it has got me puzzled as it's self-executing. Can someone help me out with this?

The only purpose of the IIFE in this scenario is to keep euler "private". Due to each file having its own context in Node, achieving this without the IIFE is quite simple.

// 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
}

Utilizing it looks like this

import { updateCamera } from './Camera'

// const camera = ..., motion = ...

updateCamera(camera, motion)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What steps can I take to ensure the browser only shows the page once it has completely loaded?

I find it frustrating when webpages load slowly and you can see the process happening. In my opinion, it would be more satisfying to wait until everything is fully loaded - scripts, images, and all - before displaying the page. This brings up two questio ...

Concealing 503 error messages within a Vue 2.0 application when making Axios HTTP requests

My Vue 2.0 application communicates with the backend through axios httpRequest. Occasionally, when the server is overloaded, I encounter the following message in the console: xhr.js:220 POST https://backend/api?param=myparam 503 I want to find a way to ...

Clicking on the title link will open the content in an iframe, but the image

Having trouble with a previous post but I've created a codepen to illustrate the issue. Hoping someone can help me out! Check out the codepen here: "https://codepen.io/Lossmann/pen/GRrXyQY" ...

What is the best way to obtain a list of all the modules that are currently accessible in AngularJS

When declaring an Angular module, I specify its dependencies as follows: const myModule = angular.module("MyModuleName", ["Dep1", "Dep2", "Dep3"]); Each dependency comes with its own set of dependencies, directives, controllers, etc. Is there a way to qu ...

Is it possible to navigate to an anchor within an HTML element that has relative positioning?

Check out the HTML code below: <li name="services"> <h1>Services</h1> <p>text</p> </li> <li name="about"> <h1>About</h1> <p> ...

jQuery.ajax Failure Response

When using MVC on the server side and calling a function with jQuery.Ajax that returns JSON, an exception is being thrown. How can I invoke the error handling function of Ajax by sending something back in the return JSON function? MVC Function public Jso ...

Challenges with ReactToPrint Library and Optimizing Layout for Thermal Printer

Working on a React.js project, I have been using the ReactToPrint library to print a specific section of my page. However, I am facing an issue where the page size remains too large and important content is being left out in the printed receipt. It seems ...

Unique 512-character string generated with Node.js

Is it possible to create a string of 512 characters in length that is truly unique? Can the nodejs built-in crypto module be used for this purpose to minimize collisions? Do you think the following sample code can achieve this goal? crypto.randomBytes(51 ...

The variable in Angular stopped working after the addition of a dependent component

Currently, I am working with Angular and have implemented two components. The first component is a navigation bar that includes a search bar. To enable the search functionality in my second component (home), I have added the following code: HTML for the n ...

What is the correct way to toggle an icon button?

Hello everyone! I need help with toggling a font-awesome icon on a button using jQuery or JavaScript. I've tried using jQuery, but the previous icon doesn't get removed from the button when toggling to the new icon. Below is the code snippet: < ...

Populate an array with the present date and proceed in reverse order

In my code, there is an array that has a specific structure: var graphData = [{ data: [[1, 1300],[2, 1600], [3, 1900], [4, 2100], [5, 2500], [6, 2200], [7, 1800]} I want to replace the numbers in the first element of each sub-array with the corresponding ...

Placing elements in Chrome compared to IE

I'm currently attempting to position elements in two rows using mathematical calculations. One of the elements, thumb_container, is a div that is absolutely positioned. Within this container, I am dynamically loading and appending image thumbnails usi ...

Utilize time in submitting a form

Is it possible to schedule a form submission at a specific time, such as 12:00? I have already created a countdown timer and now would like the form to be submitted automatically at a certain time. <html> <head> </head> <body> ...

Importing multiple modules in Typescript is a common practice

I need to include the 'express' module in my app. According to Mozilla's documentation, we should use the following code: import { Application }, * as Express from 'express' However, when using it in TypeScript and VSCode, I enc ...

Tips for managing the second datepicker for the return journey on Abhibus using Selenium webdriver

I am currently working on a code to choose departure date and return journey date, but I am encountering an issue where the return journey date is not being selected. The driver seems to be skipping over the return date selection and proceeding directly to ...

Troubleshooting Typescript compilation using tsc with a locally linked node package

In our project using React/React Native with Typescript, we have a mobile app built with React Native and a shared private package that is utilized by both the React Native client and the React frontend. Due to frequent changes in the shared package, we a ...

Utilize Google Maps API to showcase draggable marker Latitude and Longitude in distinct TextFields

I am currently utilizing the Google Maps example for Draggable markers. My objective is to showcase the latitude and longitude values within separate TextFields, where the values dynamically change as I drag the marker. Once the user stops dragging the mar ...

Get access to environment variables dynamically using parameters

I'm currently developing a Vue plugin to retrieve the content of environment variables, similar to PHP's env() method. Background: I require a URL in multiple components and have stored it in the .env file anticipating potential future changes. H ...

Tips for displaying live data in the rows of Element UI's Table

Recently, I've been working with a table that looks like this. <v-table :data="data"> <v-table-column prop="data.attribute" label="Attribute"> </v-table-column> </v-table> Instead of displaying data.attribute in the co ...

Learn the best practices for incorporating jQuery and other JavaScript libraries in your Angular2 projects

Is it possible to integrate a demo showcasing Bootstrap carousel with CSS3 animations in Angular2 using HTML, CSS, and JS? I have created my own implementation in Plunker with Angular2, but I am facing issues with the animated inner content of the carousel ...