Having trouble with implementing the Drag API Function alongside Javascript Arrow Functions?

I've searched extensively for a similar question but couldn't find one, so I hope this is not a duplicate.

Recently, I created a factory function to assist me with drag and drop functionality in my current project. However, I noticed varied behavior depending on how I structured some of the methods within it.

The complete code snippet looks like this:

  const draggables = document.querySelectorAll(draggablesSelectors);
  const containers = document.querySelectorAll(containersSelectors);

  draggables.forEach(draggableEl => {
    draggableEl.addEventListener("dragstart", dragStart, false);
    draggableEl.addEventListener("dragend", dragEnd, false);
  });

  function dragStart() {
    console.log("drag start");
  }

  function dragEnd() {
    console.log("drag end");
  }

  const returnDraggables = () => {
    return draggables;
  }

  const returnContainers = () => {
    return containers;
  }

  return {returnDraggables, returnContainers};
}

const draggableEls = Draggable(".ship", ".gameboard");

I understand that using arrow functions alters the lexical scope of 'this'. What confuses me is why I see "drag start" and "drag end" in the console when I write the dragStart and dragEnd functions as above, but they do not work at all when written as arrow functions.

Thank you!

UPDATE: Thanks to @kikon for pointing out that my function declarations were placed after the forEach loop. After rearranging them in the correct order (shown below), everything now works perfectly.

  const draggables = document.querySelectorAll(draggablesSelectors);
  const containers = document.querySelectorAll(containersSelectors);

  // Drag Functions
  const dragStart = () => {
    console.log("drag start");
  }

  const dragEnd = () => {
    console.log("drag end");
  }

  const dragDrop = () => {
    console.log("drop");
  }

  // Container Functions
  const dragOver = () => {
    console.log("drag over");
  }

  const dragEnter = () => {
    console.log("drag enter");
  }

  const dragLeave = () => {
    console.log("drag leave");
  }

  const returnDraggables = () => {
    return draggables;
  }

  const returnContainers = () => {
    return containers;
  }

  draggables.forEach(draggableEl => {
    draggableEl.addEventListener("dragstart", dragStart, false);
    draggableEl.addEventListener("dragend", dragEnd, false);
    draggableEl.addEventListener("drop", dragDrop, false);
  });

  containers.forEach(containerEl => {
    containerEl.addEventListener("dragover", dragOver, false);
    containerEl.addEventListener("dragenter", dragEnter, false);
    containerEl.addEventListener("dragleave", dragLeave, false);
  });

  return {returnDraggables, returnContainers};
}

const draggableEls = Draggable(".ship", ".gameboard");
console.log(draggableEls.returnDraggables());
export default Draggable;

Answer №1

It's possible that the issue stems from declaring/defining the handlers dragStart and dragEnd after they're already used in the forEach loop.

This setup may work with functions since they are hoisted, but it won't work with variables declared using var or const. If you had used const like for the other arrow functions, a ReferenceError would likely have occurred.

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

NodeJS buffer is not capable of handling incomplete TCP stream data

While troubleshooting my TCP JSON stream on the live server, I discovered that if the data streamed to me in JSON format is excessive, it doesn't consistently parse correctly. It requires multiple streams for successful parsing. Here is the code I am ...

Leveraging document.getElementById alongside css modules

When trying to retrieve an element that is using a css module, I encountered a problem where the id of the element changes after rendering. As a result, document.getElementById("modal") returns null. import React from "react"; export const HandleClick = ...

Using jQuery ajax in PHP, the ability to remove retrieved information from a different page is a

I'm currently working on a jQuery AJAX PHP application that allows for adding, deleting, and displaying records using switch case statements to streamline the code. Everything seems to be functioning correctly with inserting and displaying records, bu ...

The jQuery Ajax Error is consistently being triggered

I'm puzzled as to why my custom callback error function keeps getting triggered. When I remove this callback function, the success callback works just fine. Some sources online suggest that it could be an encoding issue, but I don't think that&a ...

Extending State Interface in ReactJs and Typescript: A Step-by-Step Guide

I have the following: interface EditViewState<T> { entity?: T; } abstract class EditView<T, P, S> extends React.Component<P, EditViewState<T> & S> { constructor(props: P, ctx: any) { super(props, ctx); this. ...

Learn the process of updating database information with AngularJS through a button click

As a newcomer to Angular, I am facing an issue in my mini project. The main goal of the project is to display data from a database. I have successfully set up the view to show current data by making API calls and connecting to the database. However, I am n ...

What is the process for updating JSON using TextFields?

I am currently facing an issue with my TextFields displayed within a material-ui dialog. These TextFields are initially populated by JSON data, which you can see in the example below. The problem is that once the TextFields are populated, I am unable to up ...

How can you utilize jQuery to export multiple-page HTML content into a PDF document?

I'm having trouble exporting HTML to PDF using jQuery, especially when the HTML content spans multiple pages in the PDF file. Below is my current code snippet: $("body").on("click", "#downloadPDF", function () { html2canvas($('#dow ...

Require assistance in getting a slider operational

Hello there! I could really use your assistance with this code. I have been trying to make it work using JavaScript, but I'm determined not to incorporate any external JS files. Here is the snippet of JavaScript code I am working with: "use strict"; ...

What is the best way to showcase the outcomes of a map function in JSX?

I'm currently learning react and working on implementing the searchMap function (to display movie title/poster) with the TMDB API. While I am able to successfully log the necessary information to the console, I am encountering issues such as undefined ...

What causes the updated value to be appended to an array when using the spread operator to modify an existing property's value?

In my state, I have an array of objects: const initialState=[{a:1},{b:2},{c:{d:3}}] const [state,setState]=useState(initialState) My goal is to modify the value of b to 5 within my event handler: function changeBToFive() { setState((state) => [ ...

Unable to transmit Javascript array to PHP using Ajax

I've been pulling my hair out over a seemingly simple problem. Here is the JavaScript array that's causing me trouble: var orderDetailsArray = new Array(); orderDetailsArray[0] = 'test 1'; orderDetailsArray[1] = 'test ...

Localization of text in jQuery timeago.js

I have implemented J Query time ago to display date and time on my website. I am currently working on a multilanguage website where I want the time ago message to show as "1 min ago" for English users and "1 دقیقه قبل" for Farsi users. Can I achi ...

The "track by" feature in Angular doesn't seem to be functioning properly when used with an array from $

Within the method of my factory, I am retrieving an array from the server using Angular's $resource: var resource = $resource("vm", { session: function() { return Auth.token(); }, all: '@all', vmId: '@vmId' ...

JavaScript regular expression for detecting valid characters without repeating a specific character

let rx = /(\/MxML\/[a-z0-9\[\]@/]*)/gi; let s = 'If (/MxML/trades[1]/value== 1 then /MxML/trades[type=2]/value must be /MxML/stream/pre/reference@href'; let m; let res = []; while ((m = rx.exec(s))) { res.push(m[1]); ...

The page is having trouble loading images

My goal is to display sliding images in a web application using Bootstrap carousel. The images are fetched from the backend and stored in the 'images' state. Below is the JSON format of the data that is retrieved: images:[ { SNO:'1', NA ...

Is there someone who can assist me in transforming this constructor function into a factory function using Javascript?

const createAppError = (message, status) => { return { message, status }; }; This is the equivalent code using factory functions to create an AppError with a message and status. It achieves the same result as the constructor fun ...

Traversing an array of objects to extract and display the key-value pairs for each object

Here is an array I am working with: const cuisines = [ { african: "African" }, { american: "American" }, { arabian: "Arabian" }, { argentine: "Argentine" }, { asian: "Asian" }, { asian_fusion: "Asian Fusion" }, { australian: "Australi ...

Hide the button when you're not actively moving the mouse, and show it when you start moving it

How can I make my fixed positioned button only visible when the mouse is moved, and otherwise hidden? ...

React JS: The active text object in Fabric JS canvas becomes uneditable after attaching an event listener

After implementing event listeners for copy-paste, cut-paste, and movement functionalities in different directions, I encountered an issue when trying to edit the active text object on the canvas. I am utilizing the fabricjs-react module. Below is the cod ...