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;