Error encountered: Attempting to change the mode of THREE.TransformControls, but THREE.TransformControls is not defined

I've been working with the TransformControls package (you can find it here: https://github.com/lucascassiano/three-transform-controls). While the transform controls appear to be functioning mostly fine, they are causing two major issues in my application:

1) The mode doesn't change to rotation/scaling/etc. When called, it gives an error stating: "Uncaught TypeError: Cannot read property 'setMode' of undefined".

2) A strange tangle of red lines appears on my screen along with the gizmos (please refer to the attached screenshot). both problems captured in one picture

It seems that the problem lies within the scope of the variables, but I am having trouble pinpointing it.

export default {
name: 'ThreeTest',
data() {
  return {
    mouse: new THREE.Vector2(),
    rayCaster: new THREE.Raycaster(),
    spheres: [],
    objects: [],
    intersectsPoi: null,
    transformControls: null
  };
},
methods: {
  init() {

    this.transformControls = new TransformControls(this.camera, this.renderer.domElement );


    // EVENT LISTENERS:
    map.addEventListener('mousedown', this.transformPoi, false);

    this.transformControls.addEventListener( 'change', this.render );
    this.transformControls.addEventListener( 'dragging-changed', function ( event ) {
      this.controls.enabled = ! event.value;
    } );

    window.addEventListener( 'keydown', function ( event ) {
      switch ( event.keyCode ) {
        case 81: // Q
          this.transformControls.setSpace( this.transformControls.space === "local" ? "world" : "local" );
          break;
        case 17: // Ctrl
          this.transformControls.setTranslationSnap( 100 );
          this.transformControls.setRotationSnap( THREE.Math.degToRad( 15 ) );
          break;
        case 87: // W
          this.transformControls.setMode( "translate" );
          break;
        case 69: // E
          this.transformControls.setMode( "rotate" );
          break;
        case 82: // R
          this.transformControls.setMode( "scale" );
          break;
        case 187:
        case 107: // +, =, num+
          this.transformControls.setSize( this.transformControls.size + 0.1 );
          break;
        case 189:
        case 109: // -, _, num-
          this.transformControls.setSize( Math.max( this.transformControls.size - 0.1, 0.1 ) );
          break;
        case 88: // X
          this.transformControls.showX = ! this.transformControls.showX;
          break;
        case 89: // Y
          this.transformControls.showY = ! this.transformControls.showY;
          break;
        case 90: // Z
          this.transformControls.showZ = ! this.transformControls.showZ;
          break;
        case 32: // Spacebar
          this.transformControls.enabled = ! this.transformControls.enabled;
          break;
      }
    } );

  },

  // HELPER FUNCTIONS:

  mouseOverScene (event) {
    event.preventDefault();
    let rect = event.target.getBoundingClientRect();
    let x = event.clientX - rect.left;
    let y = event.clientY - rect.top;

    this.mouse.x = ( x / this.mapWidth) * 2 - 1;
    this.mouse.y = - ( y / this.mapHeight ) * 2 + 1;

    this.rayCaster.setFromCamera(this.mouse, this.camera);
  },


  transformPoi (event) {
    console.log('I am in');
    if (event) {
      this.mouseOverScene(event);
    };

    let intersectsPoi = this.intersectsPoi;
    intersectsPoi = this.rayCaster.intersectObjects(this.spheres);
    console.log(intersectsPoi);
    let selected;

    if (intersectsPoi.length > 0 ) {
      selected = intersectsPoi[0].object;
      console.log(`The intersected is ${selected}`);
      this.transformControls.attach( selected );
      this.scene.add(this.transformControls);
    } else {
      this.transformControls.detach( selected );
      this.scene.remove(this.transformControls);
    };
  },

}

EXPECTED RESULT: The modes of the transformControls should change upon pressing the associated keys.

ACTUAL RESULT: Unfortunately, it doesn't work as expected :(

Answer №1

It seems the issue lies with this ("Uncaught TypeError: Cannot read property 'setMode' of undefined".):

window.addEventListener( 'keydown', function ( event ) {

   // In this context, 'this' may not be what you expect.
   // 'this' refers to window,
   // but window does not have transformControls
   console.log(this)
 });

An arrow function enables this to inherit from its parent function. This way, this will point to the object containing the transformControls property:

window.addEventListener( 'keydown', event => {

});

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

How to send a global variable to an event callback function in JavaScript?

I have encountered an issue in the following code where I am attempting to pass mydata to the callback function. This is just a small part of a larger problem that I am facing and I suspect it may be related to scope. Can anyone help me identify what is wr ...

Modification of navigator back function in Vue routing does not work for URLs, but functions correctly for views

Currently, I am developing a project using vue.js/vue-router (vue 3, vue-router 4). In this project, there is a slide panel that can be triggered from various views. The panel includes a "close" button to shut it. To enhance the mobile user experience whe ...

There seems to be an issue with the rangeslider.js jQuery plugin not being recognized as a function within the project. However, there are

I am currently working on integrating a Range-slider into my Django project with the help of rangeslider.js. I was able to successfully create a functional example on Codepen at https://codepen.io/Slurpgoose/pen/GRRpmpX, and everything seemed to be running ...

Vue.js - Exploring methods to append an array to the existing data

I am looking to structure my data in the following way: Category 1 Company 1 Company 2 Company 3 Category 2 Company 1 Company 2 Company 3 Below is my code snippet: getlist() { var list = this.lists; var category this.$htt ...

Using Node.JS and Socket.io to determine if a tab is currently active

Looking to add notifications to my chat feature similar to Gitter's notifications. Specifically, I want the html title to change when a new message is received. After searching online for solutions, I found that most examples involved checking if the ...

Chrome Extension with UMD Modules

The definition of the UMD module can be summarized as follows: (function (root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['exports', ' ...

Can an FAQ accordion collapse the selected element when another element is clicked?

I recently started working on a FAQ accordion project from frontendmentor. The functionality works perfectly when clicking on a question to reveal the answer and clicking again to hide it. However, I am facing an issue where if I click on one question and ...

The GLTFLoader does not support the replacement of its default materials

I am currently working on a scene that includes: AmbientLight color: light blue PointLight color: pink a gltf object loaded with textures Using the GLTFLoader, I successfully loaded a gltf object with texture map. The model is displayed correctly with ...

What are the steps to adding texture to a .fbx model in three.js?

Is it possible to dynamically alter the texture of a ".fbx" model using the Three.js library during runtime? ...

Ready for prerendering on a Gatsby site deployed with Netlify

We are encountering 504 errors on our Gatsby website hosted by Netlify. The problem stems from activating prerender.io, which often times out after 10 seconds, causing issues with Google bots detecting errors and consequently resulting in our ads being rej ...

Provide Arguments to a Function in Express JS

How's everything going? I'm curious to find out the best way, and if it's possible to send a specific parameter to an express function in NodeJS. I want to pass the string ('admin') or any other string that I choose to the 'R ...

Ordering a string of whole numbers using JavaScript

I'm currently working on a form that takes a string of numbers, splits them at each semi colon and space, sorts the numbers, and then displays the sorted list. However, when I click the button, the value in the text box doesn't get posted. Can ...

What is the reason that server.js is always excluded from the Webpack build process?

I am currently utilizing Vue.js 3 for the front end of my application, while employing Node/Express for the back-end. My goal is to implement server side rendering, but I have encountered some challenges along the way. As far as I can tell, the client-sid ...

The 'substr' property is not found in the type 'string | string[]'

Recently, I had a JavaScript code that was working fine. Now, I'm in the process of converting it to TypeScript. var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; if (ip.substr(0, 7) == "::ffff ...

Is there a way to keep the node text in place and prevent overlapping in my D3.js tree?

I'm facing an issue with long text strings in my D3 tree. The nodes move according to the tree structure, but how can I handle excessively long node-text? For instance, if the label "T-ALL" had a longer name, it could overlap with the neighboring nod ...

What distinguishes directly assigning a processed value to a variable from first assigning without processing and then processing using the && operator?

Recently, I came across a function that takes a string parameter and then carries out some operations on it. Here is an example of how it was implemented: const val = this.searchParam && this.searchParam.trim().toLowerCase(); This made me wonder why the p ...

What is the best way to retrieve data from multi-dimensional JSON structures?

Looking to extract specific values from my JSON file. console.log( objects.assignments.header.report_type ); I need to display HOMEWORK Javascript $.ajax({ url: "/BIM/rest/report/assignment", type: "POST", dataTyp ...

Optimizing the way JavaScript is incorporated into Django templates for maximum efficiency

Before, I followed this structure in a template <html> ... <script> {% include "myapp/includes/jquery-1.7.1.min.js" %} {% include "myapp/includes/myscript.js" %} </script> ... However, this resulted in all the JavaScript code being vis ...

Executing a function right away when it run is a trait of a React functional component

Having a fully functional React component with useState hooks, and an array containing five text input fields whose values are stored in the state within an array can be quite challenging. The main issue I am facing is that I need to update the inputfields ...

Automatically updating values using jQuery AJAX

My table consists of rows structured like this: <tr> <td> <div class='tempo' id='<?php print $id;?>'></div> </td> </tr> In addition, I am utilizing the following jQuery function: var ...