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

The quirks of JSON.stringify's behavior

I am in the process of gathering values to send back to an ASP.NET MVC controller action. Despite using JSON.stringify, I keep encountering Invalid JSON primitive exceptions and I am unsure why. I have a search value container named searchValues. When I i ...

JSON data not displaying correctly in bootstrap table

I've been grappling with this issue for hours now, but I'm struggling to get my bootstrap table populated correctly. Here's the snippet of my HTML: <html> <head> <link rel="stylesheet" href="https://code.jquery.com/ui/1.1 ...

The dependency graph of npm modules shows significant differences

I've been exploring the capabilities of the npm-remote-ls package to analyze dependency trees for modules. This tool is installed globally on my system. When I execute Command 1: npm-remote-ls object-assign The tree structure displayed is as follows ...

Are there more efficient methods than having to include require('mongoose') in each models file?

Is it possible to only require mongoose once in the main app.js file and then pass it to other files without loading it again? Will the script do extra work every time the same module is required? var mongoose = require('mongoose'); I'm wo ...

Generate a text input field within a dropdown menu

Below is an example of my basic HTML code for a drop-down list: <span id="Div_List"> <label for="Gender">For:</label> <select name="Gender" id="Sex"> <option value="1">1000mtr</option> <option val ...

Is it possible to generate an array of objects, where each object includes an observable retrieved through forkJoin?

let food = { id: 1, isTasty: false } Imagine I have a custom function that takes the ID of a food item and returns an observable which resolves to a boolean indicating whether the food is tasty or not. I wish to loop through an array of food items an ...

Infinite Scrolling in React: Troubleshooting Issues with the dataLength Parameter

A function called newsFeed is utilized within the useEffect hook to make a request to an endpoint for fetching posts made by the logged in user and users they follow. The retrieved data is then saved to the state: const [posts, setPosts] = useState([]) con ...

Utilize jQuery to wrap text within <b> tags and separate them with <br> tags

Upon receiving output in html string format from services, I am presented with the following: "<html>↵<h1>↵Example : ↵<br>Explanation↵</h1>↵<hr>↵<b>key1 : ABCD <br>key2 : 2016-10-18-18-38-29<br> ...

Tips on integrating TypeScript into JavaScript

Currently, I am working with a node.js server.js file. var http = require('http'); var port = process.env.port || 1337; http.createServer(function (req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res ...

Executing functionality based on changes in Angular bindings

I am working on securing user passwords in my HTML form. Currently, the password field is stored in localstorage like this: In JS: $scope.localStorage = localStorage; And then in HTML: <input id="pass" type="password" ng-model="localStorage.pass" re ...

Is there a way to incorporate jQuery into SharePoint 2010?

I am encountering an issue with linking my HTML page to our organization's SharePoint 2010 portal. All necessary files (CSS, images, jQuery) are stored in the same document library. While the CSS is functioning properly, I am facing challenges with ge ...

Is it possible to load multiple angular applications within a master angular shell application?

I am searching for a method to integrate multiple Angular applications into a single shell Angular application. The concept involves having different teams develop separate Angular apps that can be loaded within a main shell app visible to end users. Thi ...

Top method for centering a flexible SVG vertically once the page width becomes too narrow

Currently, I have two SVG images displayed side by side on a webpage. One SVG needs to maintain a fixed size while the other should scale as needed, and I have achieved this functionality. However, I am facing an issue where I want the two SVGs to align v ...

Verifying credentials using Chromium pop-up window with Playwright

In my current project, I am using Playwright to automate the configuration of multiple devices. However, I have encountered a challenge with certain models that require authentication through a popup dialog box in Chrome. https://i.stack.imgur.com/jgnYM.p ...

Switch up the animation based on the state in AngularJS

In my AngularJS application, I have implemented CSS animations for transitioning between states. The animations involve sliding content from left to right with specific timings and transforms. .content.ng-enter, .content.ng-leave { -webkit-animation-t ...

What is the preferred method for updating a variable value - Ajax or PHP?

I'm in the process of creating a dropdown survey for new visitors using cookies to collect data, but I'm a bit confused on how to implement it. If a button is clicked, the onClick event will trigger var answer1 = answer1 + 1 , or something simil ...

Having trouble with SCSS styles not being applied after refactoring to SCSS modules?

Currently, I am in the process of restructuring an application to ensure that component styles are separated from global styles using CSS modules. However, I have come across an issue where the styles are not being applied correctly. The original code sni ...

Calculating the total of fields from populated documents using Mongoose

In my application, I have two main models: User and Track. A User can complete various Tracks and earn points for each one. The schema for the User model looks like this: let userSchema = new mongoose.Schema({ name: {type: String, required: true}, ...

Utilize Google's Places Direction API Autocomplete feature to pre-select the starting location

I am currently utilizing draggable markers along with 2 autocompletes to assist with obtaining directions. You can find more information about this setup here: https://developers.google.com/maps/documentation/javascript/examples/directions-draggable. With ...

What is the best way to extract a specific object from an array containing multiple objects?

Upon entry, there is an array with various objects. A function is needed to convert this incoming array of objects into a single object. The goal is to bring it to the desired form using the function provided. var array = [ { k1:v1 }, { k2:v2 }, ...