Search code examples
javascriptangulartypescriptdrag-and-dropinteractjs

Getting undefined error for method defined


I have been trying to implement drag and drop functionality for buttons in my angular application using InteractJS

I wanted to call a method defined in class from drop event of interactable div, but getting following error.

core.js:6014 ERROR TypeError: Cannot read property 'methods' of undefined

My current code:

HTML

<div class="example-box drag-drop plugins">
        Image
</div>


<div class="dropzone">
  <h3 style="color:white;">Dropzone</h3>
</div>

TS

interact('.dropzone').dropzone({
      overlap: 0.75,
      accept: '.plugins',

      ondrop: this.onDrop,
    })

    interact('.drag-drop')
      .draggable({
        inertia: false,
        autoScroll: true
      })
  }


  methods() {
    console.log("Inside methods()");
  }

  onDrop(event) {
    event.preventDefault();
    this.methods();
  }

I have trimmed down the code to make more readable. I was guessing that maybe when event is fired angular is not in control, so this is actually undefined.


Solution

  • You need to bind the meaning of this keyword to the onDrop() event handler. Without it, the statement this.methods() is actually referring to methods() function inside the event handler. Try the following

    interact('.dropzone').dropzone({
      overlap: 0.75,
      accept: '.plugins',
    
      ondrop: this.onDrop.bind(this),          // <-- use `bind()` here
    })